splitting the dictionary values in a loop on a nested json converts them into a csv file

Here’s a recursive solution that descends into the dict. You should of course make sure that the structure is homogeneous enough to support this apprach (will fail if you are missing nested dictionaries):

import pandas as pd

jsonFile = {
         '7': {
               '11': {'ref1': 1}
              }, 

         '5': {
               '15':  {'ref1':0, 'ref3':1},
               '17':  {'ref2':1}, 
               '19':  {'ref1':1,'ref4':0}
              }, 

        '3': {
               '21':  {'ref3':1, 'ref2':1}, 
               '14':  {'ref5':0}
             }
}

def flatten_dict(d, parent_keys=None):
    parent_keys = parent_keys or []
    for k, v in d.items():
        if isinstance(v, dict):
            for values in flatten_dict(v, parent_keys=parent_keys + [k]):
                yield values
        else:
            yield parent_keys + [k, v]

df = pd.DataFrame(list(flatten_dict(jsonFile)), columns=("key", "subkey", "references", "values"))
df

Output:

    key subkey  references  values
0   7   11      ref1        1
1   5   15      ref1        0
2   5   15      ref3        1
3   5   17      ref2        1
4   5   19      ref1        1
5   5   19      ref4        0
6   3   21      ref3        1
7   3   21      ref2        1
8   3   14      ref5        0

Then you can finish this up with df.to_csv().

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top