简体   繁体   English

如何从python dict生成特定的JSON?

[英]How to generate specific JSON from python dict?

I want to create json data which exactly looks like this:我想创建完全如下所示的 json 数据:

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

The data "number" and "instock" are read from python dict:数据"number""instock"是从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.我只是缺少"mainDetail" ,我的想法陷入僵局。 What can I do to make it work?我该怎么做才能让它发挥作用?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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