Python用子数组动态构建JSON

时间:2016-03-31 23:33:33

标签: python json dynamic

我可以从简单的字典{}和List []构建JSON,但是当我尝试构建更复杂的结构时。我在输出JSON中嵌入了'\'。

我想要的结构:

{"name": "alpha",
 "results": [{"entry1": 
        [
        {"sub1": "one"}, 
        {"sub2": "two"}
        ]
    }, 
    {"entry2": 
        [
        {"sub1": "one"}, 
        {"sub2": "two"}
        ]
    }
]
}

这就是我得到的:

   {'name': 'alpha',
    'results': '[{"entry1": "[{\\\\"sub1\\": \\\\"one\\\\"}, {\\\\"sub2\\\\": '
            '\\\\"two\\\\"}]"}, {"entry2": "[{\\\\"sub1\\\\": \\\\"one\\\\"}, 
    {\\\\"sub2\\\\": '
            '\\\\"two\\\\"}]"}]'}

注意嵌入式\\。每次代码通过json.dumps时,都会追加另一个\。

这里的代码几乎可以使用,但不会:

import json
import pprint
testJSON = {}

testJSON["name"] = "alpha"

#build sub entry List
entry1List = []
entry2List = []
topList = []
a1 = {}
a2 = {}
a1["sub1"] = "one"
a2["sub2"] = "two"

entry1List.append(a1)
entry1List.append(a2)

entry2List.append(a1)
entry2List.append(a2)

# build sub entry JSON values for Top List
tmpDict1 = {}
tmpDict2 = {}
tmpDict1["entry1"] = json.dumps(entry1List)
tmpDict2["entry2"] = json.dumps(entry2List)
topList.append(tmpDict1)
topList.append(tmpDict2)

# Now lets' add the List with 2 sub List to the JSON
testJSON["results"] = json.dumps(topList)

pprint.pprint (testJSON)

1 个答案:

答案 0 :(得分:3)

看看这一行:

tmpDict1["entry1"] = json.dumps(entry1List)

这指定key entry1具有将entry1List转换为json的字符串输出的值。实质上,它将JSON放在JSON字符串中,因此它被转义。为了嵌套数据结构,我选择:

tmpDict1["entry1"] = entry1List

与其他地方相同。一旦有一个列表和序列树 - 您只需要在根容器(dict或列表)上调用json.dumps()一次。