简体   繁体   中英

How can i convert python nested dictionary to json file?

I have a python nested dictionary in the following format

data = {
        'item1': {
            'name': "A",
            'price': 10
        },
        'item2': {
            'name': "B",
            'price': 20
        }
    }

My expected output JSON file will be the following format

[
  {
    "name": "A",
    "price": 10
  },
  {
    "name": "B",
    "price": 20
  }
]

My code is

data = {
    'item1': {
        'name': "A",
        'price': 10
    },
    'item2': {
        'name': "B",
        'price': 20
    }
}
with open("my.json", "w") as f:
    json.dump(data, f)

But this code can't generate my expected JSON output format, how can i do it?

The problem is not about JSON but about having a dictionary and expecting a list. You can convert your dictionary entries to a list with list(data.values()) and then export it to JSON.

import json
data = {
'item1': {
    'name': "A",
    'price': 10
    },
'item2': {
    'name': "B",
    'price': 20
    }
}

print(list(data.values()))
json.dump(list(data.values()), f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM