【问题标题】:Append(Map) keys from json array to another son array将 json 数组中的键附加(映射)到另一个子数组
【发布时间】:2019-09-26 12:33:42
【问题描述】:

我有 2 个json 文件:

file1.json

[
 {
  "name":"value",
  "description":"value"
 },
 {
  "name":"value1",
  "description":"value1"
 }
]

file2.json

[
 {
  "url":"value"   
 },
 {
  "url":"value1"
 }
]

预期结果:

[
 {
  "name":"value",
  "description":"value"
  "url":"value"

 },
 {
  "name":"value1",
  "description":"value1",
  "url":"value1"
 }
]

我试过jq

jq -s '.[0] * .[1]' file1 file2

我尝试使用 python,但我不熟悉,它不起作用。提前谢谢。

【问题讨论】:

  • 供您考虑,或者可以使用 walk-path unix 实用程序 jtc 实现相同的 JSON 合并:<file1.json jtc -w[:] -mi file2.json -i[:] - 将为您提供相同的结果。或者,如果您想将更改直接应用到源文件中(让它成为 file1.json):jtc -w[:] -mi file2.json -i[:] -f file1.json。如果您愿意,我可以在单独的答案中详细说明用法。 (我是该工具的开发人员)。

标签: python json jq transpose


【解决方案1】:

试试这个:

import json
li=[]
with open('file1.json') as f:
    li1 = json.load(f)
with open('file2.json') as f:
    li2 = json.load(f)
for a in zip(li1,li2):  # where l1 is first list, l2 is second list
    dict={}
    dict.update(a[0])
    dict.update(a[1])
    li.append(dict)

print(li)
# [{'name': 'value', 'description': 'value', 'url': 'value'}, {'name': 'value1', 'description': 'value1', 'url': 'value1'}]

from collections import ChainMap
import json
with open('file1.json') as f:
    li1 = json.load(f)
with open('file2.json') as f:
    li2 = json.load(f)
li=[dict(ChainMap(*a)) for a in zip(li1,li2)]
print(li)

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    有了 jq,感谢transpose,它是单行的:

        jq -s 'transpose | map(add)' file1.json file2.json 
    
    [
      {
        "name": "value",
        "description": "value",
        "url": "value"
      },
      {
        "name": "value1",
        "description": "value1",
        "url": "value1"
      }
    ]
    

    【讨论】:

      猜你喜欢
      • 2015-07-14
      • 2017-05-26
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      相关资源
      最近更新 更多