0

I need to convert this DataFrame to json file. enter image description here

Code:

def new_json(df):
    drec = dict()
    ncols = df.values.shape[1]
    for line in df.values:
        d = drec
        for j, col in enumerate(line[:-1]):
            if not col in d.keys():
                if j != ncols-2:
                    d[col] = {}
                    d = d[col]
                else:
                    d[col] = line[-1]
            else:
                if j!= ncols-2:
                    d = d[col]
    return drec

a=new_json(df)
print(a)

result:

{'a': {'a2': {'a21': 'new', 'a22': 'old'}, 'a3': {'a31': 'content'}, 'a4': {'a41': 'old'}}, 'b': {'b1': {'b11': 'content', 'b12': 'new', 'b13': 'new'}}, 'c': {'c1': {'c11': 'content'}, 'c2': {'c21': 'content'}, 'c3': {'c31': 'old'}}}

Is it possible to modify the result in this json format?

{
    'a': {
         'a2': {
            'a21': 'new', 
            'a22': 'old'
               },
         'a3': {
             'a31': 'content'
               },
         'a4': {
             'a41': 'old'
                }
         },
    'b': {
        'b1': {
            'b11': 'content', 
            'b12': 'new', 
            'b13': 'new'
               }
         },
    'c': {
        'c1': {
            'c11': 'content'
              },
        'c2': {
            'c21': 'content'
               },
        'c3': {
            'c31': 'old'
              }
         }
}
Ching
  • 135
  • 1
  • 9
  • Its a bit unclear what "modify the result" means. Do you mean can you change the d/drec dict? Yes, you can, python dicts are mutable. You can both add new keys and change values for existing ones. – code11 Dec 09 '20 at 15:28
  • Bother of these dictionaries are the same; just printed differently. You also mention JSON which (technically) you don't use in your code. Is your question about formatting the output, or something else? – Simon Brahan Dec 09 '20 at 15:30
  • Hi! I mean formatting the output, sorry for being unclear. @SimonBrahan – Ching Dec 09 '20 at 15:32
  • @code11 The result is good already, just want the structure to look like the lower one. – Ching Dec 09 '20 at 15:34
  • 1
    Ah, so its just to pretty print the json. I'd check out [this question](https://stackoverflow.com/q/12943819/1456253) then. – code11 Dec 09 '20 at 18:22

0 Answers0