简体   繁体   中英

How to generate specific JSON from python dict?

I want to create json data which exactly looks like this:

[
      {
        "mainDetail": {
            "number": "12345",    
            "inStock": 111
        }
      },
      {
        "mainDetail": {
            "number": "54321",
            "inStock": 222
        }
      }
]

The data "number" and "instock" are read from python dict:

articleDict = {}
d=[{'number': x, 'inStock': y} for x,y in articleDict.items()]
print json.dumps(d, indent=4)

This is what i get so far:

[
    {
        "number": "12345",
        "inStock": 111
    },
    {
        "number": "54321",
        "inStock": 222
    }
]

I am just missing the "mainDetail" , I'm at an impasse with my ideas. What can I do to make it work?

d=[{"mainDetail" : {'number': x, 'inStock': y}} for x,y in articleDict.items()]

创建列表时,您需要添加此“mainDetail”。

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