【发布时间】:2020-08-19 04:30:03
【问题描述】:
我有两个 JSON。有这样的条目:
one.json
"data": [
{
"results": {
"counties": {
"32": 0,
"96": 0,
"12": 0
},
"cities": {
"total": 32,
"reporting": 0
}
},
"element_id": 999
},
另一个有这样的条目:
两个.json
"data": [
{
"year": 2020,
"state": "Virginia",
"entries": [
{
"first_name": "Robert",
"last_name": "Smith",
"entry_id": 15723,
"pivot": {
"county_id": 32,
"element_id": 999
}
},
{
"first_name": "Benjamin",
"last_name": "Carter",
"entry_id": 15724,
"pivot": {
"county_id": 34,
"element_id": 999
}
}
],
"element_id": 999,
},
我想根据element_id 将 one.json 加入 two.json。 JSON 有很多 element_ids,因此有一个元素可以找到要附加的正确的。有没有办法基于element_id 使用append 来做到这一点而不必使用for 循环?上面第二个 JSON 的附加版本如下所示:
joined.json
"data": [
{
"year": 2020,
"state": "Washington",
"entries": [
{
"first_name": "Robert",
"last_name": "Smith",
"entry_id": 15723,
"pivot": {
"county_id": 32,
"element_id": 999
}
},
{
"first_name": "Benjamin",
"last_name": "Carter",
"entry_id": 15724,
"pivot": {
"county_id": 34,
"element_id": 999
}
}
],
"element_id": 999,
{
"results": {
"counties": {
"32": 0,
"96": 0,
"12": 0
},
"cities": {
"total": 32,
"reporting": 0
}
},
},
到目前为止我所拥有的:
for item in one:
#this goes through one and saves each unique item in a couple variables
temp_id = item["element_id"]
temp_datachunk = item
#then I try to find those variables in two and if I find them, I append
for data in two:
if data["element_id"] == temp_id:
full_data = data.append(item)
print(full_data)
现在,我的尝试在 append 处死去。我得到AttributeError: 'dict' object has no attribute 'append'。
【问题讨论】:
-
到目前为止你有什么尝试?
-
@KlausD。已经更新了我尝试过的内容。
标签: python json parsing merge append