我可以從簡單字典{}和List []構建JSON,但是當我嘗試構建更復雜的結構時。我在輸出JSON中嵌入'\'。Python動態構建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)
您將編碼的JSON嵌入字典中,然後重新編碼已編碼的JSON。如果你想「合併」JSON,只需「合併」dictts –
簡單地說:首先以Pyhon字典或列表的形式構建數據,最後使用'json.dumps(data)'將其轉換爲JSON。 JSON不是特殊的數據類型,它是以字符串形式表示某些數據的序列化方法。 –