将JSON数据与Python合并
作为Python程序的一部分,我希望合并包含相同结构数据的JSON对象。例如:将JSON数据与Python合并,python,json,Python,Json,作为Python程序的一部分,我希望合并包含相同结构数据的JSON对象。例如: { "responseStatus": "SUCCESS", "responseDetails": { "total": 5754, }, "data": [ { "id": 1324651 }, { "id": 5686131 } ] } 我要做的
{
"responseStatus": "SUCCESS",
"responseDetails": {
"total": 5754,
},
"data": [
{
"id": 1324651
},
{
"id": 5686131
}
]
}
我要做的是将节对象的数据数组的内容添加到第一个对象的数据数组中
因此,假设:
thejson1 = json.loads({"responseStatus": "SUCCESS","responseDetails": {"total": 5754,},"data": [{"id": 1324651},{"id": 5686131}]})
thejson2 = json.loads({"responseStatus": "SUCCESS","responseDetails": {"total": 1234,},"data": [{"id": 2165735},{"id": 2133256}]})
我认为:
thejson1["data"].append(thejson2["data"])
将JSON1扩展为:
{
"responseStatus": "SUCCESS",
"responseDetails": {
"total": 5754,
},
"data": [
{
"id": 1324651
},
{
"id": 5686131
},
{
"id": 2165735
},
{
"id": 2133256
}
]
}
但它所做的是将JSON2数据作为数组添加到JSON1的数据数组中:
{
"responseStatus": "SUCCESS",
"responseDetails": {
"total": 5754,
},
"data": [
{
"id": 1324651
},
{
"id": 5686131
},
[
{
"id": 2165735
},
{
"id": 2133256
}
]
]
}
那么,我做错了什么?看起来append添加了第二个JSON对象的数据数组,而不是它的内容,但请注意,我无法预先知道JSON输入中“data”数组的内容,因此我无法编写专门循环“id”对象以逐个添加它们的代码
提前谢谢
R.您要查找的是
extend
,而不是append
thejson1["data"].extend(thejson2["data"])
append
接受单个参数并将其插入末尾。而extend
则通过将参数列表中的所有单个值添加到末尾来扩展列表
# example:
a=[1, 2, 3]
b = a[:].append([4, 5])
# b = [1, 2, 3, [4, 5]]
c = a[:].extend([4, 5])
# c = [1, 2, 3, 4, 5]
您要查找的是
extend
,而不是append
thejson1["data"].extend(thejson2["data"])
append
接受单个参数并将其插入末尾。而extend
则通过将参数列表中的所有单个值添加到末尾来扩展列表
# example:
a=[1, 2, 3]
b = a[:].append([4, 5])
# b = [1, 2, 3, [4, 5]]
c = a[:].extend([4, 5])
# c = [1, 2, 3, 4, 5]
输出:
{'responseDetails': {'total': 5754}, 'data': [{'id': 1324651}, {'id': 5686131}, {'id': 2165735}, {'id': 2133256}], 'responseStatus': 'SUCCESS'}
您还可以使用+=
来扩展
输出:
{'responseDetails': {'total': 5754}, 'data': [{'id': 1324651}, {'id': 5686131}, {'id': 2165735}, {'id': 2133256}], 'responseStatus': 'SUCCESS'}
您还可以使用+=
来扩展 可能的重复可能的重复