'Encoding python dictionary into JSON using a schema

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source