Advertisement
Guest User

Untitled

a guest
Dec 14th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1.  
  2. up vote
  3. 1
  4. down vote
  5. accepted
  6. A hardcoded example...
  7.  
  8. import pandas as pd
  9.  
  10. temp = [{
  11. "ID": "123456",
  12. "profile": {
  13. "criteria": [
  14. {
  15. "type": "type1",
  16. "name": "name1",
  17. "value": "7",
  18. "properties": []
  19. },
  20. {
  21. "type": "type2",
  22. "name": "name2",
  23. "value": "6",
  24. "properties": [
  25. {
  26. "type": "MAX",
  27. "name": "",
  28. "value": "100"
  29. },
  30. {
  31. "type": "MIN",
  32. "name": "",
  33. "value": "5"
  34. }
  35. ]
  36. },
  37. {
  38. "type": "type3",
  39. "name": "name3",
  40. "value": "5",
  41. "properties": []
  42. }
  43. ]
  44. }
  45. },
  46. {
  47. "ID": "456789",
  48. "profile": {
  49. "criteria": [
  50. {
  51. "type": "type4",
  52. "name": "name4",
  53. "value": "6",
  54. "properties": []
  55. }
  56. ]
  57. }
  58. }]
  59.  
  60. cols = ['ID', 'criteria', 'type', 'name', 'value']
  61.  
  62. rows = []
  63. for data in temp:
  64. data_id = data['ID']
  65. criteria = data['profile']['criteria']
  66. for d in criteria:
  67. rows.append([data_id, criteria.index(d)+1, *list(d.values())[:-1]])
  68.  
  69. df = pd.DataFrame(rows, columns=cols)
  70. This is by no means elegant. It is more of a quick and dirty solution, as I don't know how the JSON data is exactly formatted - however, based on what you've provided, my code above will produce the desired DataFrame.
  71.  
  72. ID criteria type name value
  73. 0 123456 1 type1 name1 7
  74. 1 123456 2 type2 name2 6
  75. 2 123456 3 type3 name3 5
  76. 3 456789 1 type4 name4 6
  77. Additionally, if you need to 'load' the JSON data, you can use the json library like so:
  78.  
  79. import json
  80.  
  81. temp = json.loads(json_string)
  82.  
  83. # Or from a file...
  84. with open('some_json.json') as json_file:
  85. temp = json.load(json_file)
  86. Please note the difference between json.loads and json.load.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement