so i have a nested json that contains two groups , each group has a field that contains more sub groups i would like to pop all the sub groups out to flatten the json and remove the sub groups field
What is the correct way to do it
JSON :
[ { "groupId": "a_group", "version": "2.0.1", "type": "jar", "sub_group": [ { "groupId": "a_1", "version": "2.0.0", "type": "jar", "sub_group": [] }, { "groupId": "a_2", "version": "2.0.1", "type": "jar", "sub_group": [ { "groupId": "a_1", "version": "2.0.0", "type": "jar", "sub_group": [] }, ], } ], }, { "groupId": "c_group", "version": "1.9.1", "type": "jar", "sub_group": [ { "groupId": "a_1", "version": "2.0.0", "type": "jar", "sub_group": [] }, ], }, }
This is the expected result: I need to pop all the sub groups and make them appear as a flat json like this
[{ "groupId": "a_group", "version": "2.0.1", "type": "jar", "sub_group": [] }, { "groupId": "a_1", "version": "2.0.0", "type": "txt", "sub_group": [] }, { "groupId": "a_2", "version": "2.0.1", "type": "jar", "sub_group": [] }, { "groupId": "c_group", "version": "1.9.1", "type": "jar", "sub_group": [] }, ]
Advertisement
Answer
Well , i had an interview question very similar to your question
This is my answer:
def flatten_json(self,json_data) ->json: ''' :param json_data: The json file to work on :return: A json ''' out = [] def flatten(key): if isinstance(key, dict): if key['sub_group']: flatten(key['sub_group']) key['sub_group'] = [] out.append(key) else: out.append(key) # in case we have multiple items in the list[] elif isinstance(key, list): for val in key: flatten(val) flatten(json_data) return json.dumps(out)
This is not the nicest solution but it works pretty good I took the liberty of assuming the name of the sub_group is always subgroup I used a recursion and i am handling moving into the dictionaries with the isinstance method to check if i am looking at a dictionary , if not then it means i have a list containing something else I handle that in the elif part and i iterate over each item in the list