Home > Mobile >  Creating a JSON text file from a nested dictionary
Creating a JSON text file from a nested dictionary

Time:02-02

I am creating a JSON file of a nested dictionary. My code is currently as follows:

myfamily = {
  "child1" : {
    "name" : "Emil"
  },
  "child2" : {
    "name" : "Tobias"
  },
  "child3" : {
    "name" : "Linus"
  }
}

names = []
for i in myfamily.values():
    print(type(i))
    print(i)
    s = json.dumps(i)
    names.append(s)
    

df_family = pd.DataFrame()

df_family['Child'] = myfamily.keys()
df_family['Name'] = values 
text = df_family.to_json(orient='records')
print(text)

This leads to the following output:

[{"Child":"child1","Name":"{\"2022\": 50, \"2023\": 50, \"2024\": 0}"},{"Child":"child2","Name":"{\"2022\": 50, \"2023\": 50, \"2024\": 50}"},{"Child":"child3","Name":"{\"2022\": 0, \"2023\": 100, \"2024\": 0}"}]

So my question is, why are these slashes added and is this the correct way to create a JSON text format of a nested dictionary?

CodePudding user response:

import json

myfamily = {
  "child1" : {
    "name" : "Emil"
  },
  "child2" : {
    "name" : "Tobias"
  },
  "child3" : {
    "name" : "Linus"
  }
}

def nested_json(dict_t,fist_key="Child"):
  list_t= []
  for key,val in myfamily.items():
    nested_key = next(iter( val.keys()))
    list_t = [{
        fist_key:key,
        nested_key:val[nested_key]
    }]
  return json.dumps(list_t)


nested_json(myfamily)
  •  Tags:  
  • Related