Skip to content
Advertisement

python – json , how to make a json flat

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 :

JavaScript

This is the expected result: I need to pop all the sub groups and make them appear as a flat json like this

JavaScript

Advertisement

Answer

Well , i had an interview question very similar to your question

This is my answer:

JavaScript

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement