JSON - 在 python 中循环生成一个 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18673952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:24:20  来源:igfitidea点击:

JSON - Generating a json in a loop in python

pythonjson

提问by Below the Radar

I have some difficulties generating a specific JSON object in python.

我在 python 中生成特定的 JSON 对象时遇到了一些困难。

I need it to be in this format:

我需要它是这种格式:

[
   {"id":0 , "attributeName_1":"value" , "attributeName_2":"value" , .... },
   {"id":1 , "attributeName_2":"value" , "attributeName_3":"value" , .... },
   .
   .
   .
]

In python, im getting the ids, attributeNames and values from 2 objects. Im trying to generate the json like this:

在 python 中,我从 2 个对象中获取 id、attributeName 和值。我试图生成这样的json:

    data=[]
    for feature in features_selected:
        data.append({"id":feature.pk})
        for attribute in attributes_selected:
            if attribute.feature == feature:
                data.append({attribute.attribute.name : attribute.value})
        jsonData=json.dumps(data)

but I got this result which is not exactly what I need:

但我得到的结果并不完全是我需要的:

[
   {"id":0} , {"attributeName_1":"value"} , {"attributeName_2":"value"} ,
   {"id":1} , {"attributeName_2":"value"} , {"attributeName_3":"value"} , .... },
   .
   .
   .
]

采纳答案by alecxe

The problem is that you are appending to datamultiple times in the loop: first {"id":feature.pk}, then {attribute.attribute.name : attribute.value}in the inner loop.

问题是您data在循环中多次追加: first {"id":feature.pk},然后{attribute.attribute.name : attribute.value}在内部循环中。

Instead, you need to define a dictionary inside the loop, fill it with iditem and attributes and only then append:

相反,您需要在循环内定义一个字典,用id项目和属性填充它,然后才附加:

data=[]
for feature in features_selected:
    item = {"id": feature.pk}
    for attribute in attributes_selected:
        if attribute.feature == feature:
            item[attribute.attribute.name] = attribute.value
    data.append(item)

jsonData=json.dumps(data)