JSON - 在python中生成循环中的json

时间:2013-09-07 13:45:15

标签: python json

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

我需要它采用这种格式:

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

在python中,我从2个对象获取id,attributeNames和值。我试图像这样生成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)

但我得到的结果并不完全符合我的要求:

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

1 个答案:

答案 0 :(得分:16)

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

相反,你需要在循环中定义一个字典,用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)