I am struggling to encode json from a python dictionary. When using json.dumps on a dictionary there is no way to tell the function what objects and properties to map the dictionary keys and values to.
The result of the blind dump is that I end up with schemaless json with unique keys rather than a coherent json structure
import json
d = {
"Laptop": {
"sony": 1,
"apple": 2,
"asus": 5,
},
"Camera": {
"sony": 2,
"sumsung": 1,
"nikon" : 4,
},
}
with open("my.json","w") as f:
json.dump(d,f)
Which returns
{"Laptop": {"sony": 1, "apple": 2, "asus": 5}, "Camera": {"sony": 2, "sumsung": 1, "nikon": 4}}
which looks like json, but has no schema at all.
i am looking to produce a json file more like this
{"devices": [
{"device": {
"deviceType": "Laptop",
"deviceBrands": [
{"deviceBrand": {
"deviceBrandName": "sony",
"deviceBrandCount": "1"
},
{"deviceBrand": {
"deviceBrandName": "apple",
"deviceBrandCount": "2"
},
{"deviceBrand": {
"deviceBrandName": "asus",
"deviceBrandCount": "5"
}
},
{"device": {
"deviceType": "Camera",
"deviceBrands": [
{"deviceBrand": {
"deviceBrandName": "sony",
"deviceBrandCount": "2"
},
{"deviceBrand": {
"deviceBrandName": "sumsung",
"deviceBrandCount": "1"
},
{"deviceBrand": {
"deviceBrandName": "nikon",
"deviceBrandCount": "5"
}
}
}
Any recommendations?
CodePudding user response:
Create the structure you want using a dictionary comprehension before calling json.dump
:
output = {"devices": [
{"device": {"deviceType": k,
"deviceBrands": [{"deviceBrand": {"deviceBrandName": k1,
"deviceBrandCount": v1}
} for k1, v1 in v.items()
]
}
}
for k,v in d.items()]}
with open("output.json","w") as f:
json.dump(output,f)
output.json:
{
"devices": [
{
"device": {
"deviceType": "Laptop",
"deviceBrands": [
{
"deviceBrand": {
"deviceBrandName": "sony",
"deviceBrandCount": 1
}
},
{
"deviceBrand": {
"deviceBrandName": "apple",
"deviceBrandCount": 2
}
},
{
"deviceBrand": {
"deviceBrandName": "asus",
"deviceBrandCount": 5
}
}
]
}
},
{
"device": {
"deviceType": "Camera",
"deviceBrands": [
{
"deviceBrand": {
"deviceBrandName": "sony",
"deviceBrandCount": 2
}
},
{
"deviceBrand": {
"deviceBrandName": "sumsung",
"deviceBrandCount": 1
}
},
{
"deviceBrand": {
"deviceBrandName": "nikon",
"deviceBrandCount": 4
}
}
]
}
}
]
}