如何在公共密钥的基础上加入2个json文件

2024-06-08 08:22:02 发布

您现在位置:Python中文网/ 问答频道 /正文

输入测试.json-你知道吗

{"strikers": [
    { "name": "Alexis Sanchez", "club": "Manchester United" },
    { "name": "Robin van Persie", "club": "Feyenoord" }
] }

test1.json文件

{"strikers": [
    { "name": "Nicolas Pepe", "club": "Arsenal" }
] }

预期产量结果.json你知道吗

{"strikers": [
    { "name": "Alexis Sanchez", "club": "Manchester United" },
    { "name": "Robin van Persie", "club": "Feyenoord" },
    { "name": "Nicolas Pepe", "club": "Arsenal" }
] }

我的输出

{"strikers": [

    { "name": "Alexis Sanchez", "club": "Manchester United" },
    { "name": "Robin van Persie", "club": "Feyenoord" }
    ] }, 
    {"strikers": [
        { "name": "Nicolas Pepe", "club": "Arsenal" }
] } 

我已经写了这段代码,不知道如何前进。有人能帮我吗?你知道吗

def mangle(s):
    return s.strip()[1:-1]

input_filenames = ["test.json", "test1.json"]
with file("result.json", "w") as outfile:
    first = True
    for infile_name in input_filenames:
        with file(infile_name) as infile:
            if first:
                outfile.write('[')
                first = False
            else:
                outfile.write(',')
            outfile.write(mangle(infile.read()))
    outfile.write(']')

Tags: namejsonvaninfileoutfilewriterobinunited
3条回答

交互式演示:https://repl.it/repls/DullBeneficialConcentrate

import json

input_filenames = ["test.json", "test1.json"]

def read_json(file):
  with open(file, 'r') as f:
    return json.load(f)

data = [read_json(fn) for fn in input_filenames]

for k in data[0]:
  data[0][k].extend(data[1][k])

with open('result.json', 'w') as f:
  json.dump(data[0], f, indent=2)

你知道吗结果.json地址:

{
  "strikers": [
    {
      "name": "Alexis Sanchez",
      "club": "Manchester United"
    },
    {
      "name": "Robin van Persie",
      "club": "Feyenoord"
    },
    {
      "name": "Nicolas Pepe",
      "club": "Arsenal"
    }
  ]
}

使用json.load()解析JSON,使用json.dump()编写JSON。然后连接属性。你知道吗

all_data = {}
for file in input_filenames:
    with open(file, "r") as f:
        data = json.load(f)
    for key in data:
        if key in all_data:
            all_data[key] += data[key]
        else:
            all_data[key] = data[key]

with open("result.json", "w") as outfile:
    json.dump(outfile, all_data)

这段代码假设JSON中的所有属性都是需要连接的列表。你知道吗

python有一个有用的json库,您可以这样做:

import json
json1 = '''{"strikers": [
    { "name": "Alexis Sanchez", "club": "Manchester United" },
    { "name": "Robin van Persie", "club": "Feyenoord" }
    ] }'''

json2 = '''{"strikers": [
    { "name": "Nicolas Pepe", "club": "Arsenal" }
    ] }'''

strikers_dict = json.loads(json1)
strikers_dict['strikers'].extend(json.loads(json2)['strikers'])

print(json.dumps(strikers_dict, indent=2))

这个指纹

{
  "strikers": [
    {
      "name": "Alexis Sanchez",
      "club": "Manchester United"
    },
    {
      "name": "Robin van Persie",
      "club": "Feyenoord"
    },
    {
      "name": "Nicolas Pepe",
      "club": "Arsenal"
    }
  ]
}

相关问题 更多 >