0

EDIT: It should not output "notThis", because it has no inner elements.

EDIT: This post is not a duplicate as it asks for parsing the inner elements and it only asks parsing elements without inner elements.

I would like to put the root elements of a JSON array in a seperate array. Thereby I'd also like to parse the names of it's inner elements, and put them in an array with arrays of the inner elements.

See the following example:

[
  {
    "firstRoot": {
      "firstInner1": "test",
      "secondInner1": "test"
    }
  },
  {
    "secondRoot": {
      "firstInner2": "test",
      "secondInner2": "test"
    }
  },
  {
    "thirdRoot": {
      "firstInner3": "test",
      "secondInner3": "test"
    }
  }, {"notThis" : "test"}
]

Desired output: An array with names of all root elements:

["firstRoot", "secondRoot", "thirdRoot"]

some arrays with inner elements:

[["firstInner1","secondInner1"],["firstInner2","secondInner2"],["firstInner3","secondInner3"]]

So without the "notThis" element, because it has no inner elements.

Chiel
  • 662
  • 1
  • 7
  • 30
  • How would you do it with `for` loops? – timgeb Nov 27 '18 at 12:48
  • I have basic knowledge about Python currently. I know how to create a dict, and how to access certain elements. However, I have no idea about finding the root elements without hard coding it. Therefore, I posted it on stack overflow. – Chiel Nov 27 '18 at 12:57
  • Possible duplicate of [Extract all keys from a list of dictionaries](https://stackoverflow.com/questions/11399384/extract-all-keys-from-a-list-of-dictionaries) – Kunal Mukherjee Nov 27 '18 at 13:17
  • This question is different in the way that it also asks for parsing of inner element names. – Chiel Nov 27 '18 at 13:21

2 Answers2

1

Something like this? Might not be the optimal solution.

#Load JSON
json_str = '[{"firstRoot":{"firstInner1":"test","secondInner1":"test"}},{"secondRoot":{"firstInner2":"test","secondInner2":"test"}},{"thirdRoot":{"firstInner3":"test","secondInner3":"test"}}]'
dic = json.loads(json_str)

#Output arrays
root_ele = []
inner_ele = []

#Parse JSON
for i in dic:
    root_ele.append(list(i.keys())[0])
    y = [k for j in list(i.values()) for k, l in j.items()]
    inner_ele.append(y)

#Print output
print(root_ele)
print(inner_ele)

Output:

['firstRoot', 'secondRoot', 'thirdRoot']
[['firstInner1', 'secondInner1'], ['firstInner2', 'secondInner2'], ['firstInner3', 'secondInner3']]
Srce Cde
  • 1,764
  • 10
  • 15
1

I'd map a lambda over json entries:

json_dict = {...}
list(map(lambda j: list(j.keys())[0], json_dict))
# ['firstRoot', 'secondRoot', 'thirdRoot']
mehdix
  • 4,984
  • 1
  • 28
  • 36