python - 使用 Python 加入两个基于 ID 元素的 JSON
问题描述
我有两个 JSON。一个有这样的条目:
一个.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,
},
我想将 one.json 加入到 two.json 基于element_id
. JSON 有很多element_id
s,因此有一个元素可以找到要附加到的正确的。有没有一种方法可以在不必使用 for 循环的情况下append
做到这一点?element_id
上面第二个 JSON 的附加版本如下所示:
加入.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'
。
解决方案
像这样的东西应该工作:
source = '''
[{
"results": {
"counties": {
"32": 0,
"96": 0,
"12": 0
},
"cities": {
"total": 32,
"reporting": 0
}
},
"element_id": 999
}]
'''
target = """
[{
"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
}]
"""
source_j = json.loads(source)
target_j = json.loads(target)
jsonpath_expr = parse('$..element_id')
source_match = jsonpath_expr.find(source_j)
target_match = jsonpath_expr.find(target_j)
if source_match[0].value==target_match[0].value:
final = target_j+source_j
print(final)
输出是组合的 json。
推荐阅读
- java - GridLayout 似乎不在设计视图上
- python - 转换为超级组时,电报聊天 ID 是否保持不变?
- node.js - 在投资组合网站上创建 github 仪表板
- javascript - .setAttribute 在 for 循环中不起作用 - JavaScript
- django - Django - 表单数据不会保存到数据库
- node.js - app.post 正在工作,但 app.use 没有。快速节点
- javascript - 延迟 n 秒重试轮询服务
- r - R- 无效或过期的令牌
- here-api - 这里 api 请求错误 --- 无效的凭据
- amazon-web-services - 如何在单个 API 网关后面合并多个微服务?