读取 JSON 文件并将 JSON 个对象附加到 JSON 数组

Read a JSON file and append JSON objects to a JSON Array

我有一个 JSON 文件 name.json,内容如下,

{
    "Name": [{
        "firstName": "John",
        "lastName": "Stark"
    }]
}

使用 python 如何使用以下列表将 Stark 家族的成员添加到 JSON 文件 firstNameList=['Sansa','Arya','Brandon']

预期输出

{
    "Name": [{
            "firstName": "John",
            "lastName": "Stark"
        },
        {
            "firstName": "Sansa",
            "lastName": "Stark"
        },
        {
            "firstName": "Arya",
            "lastName": "Stark"
        },
        {
            "firstName": "Brandon",
            "lastName": "Stark"
        }
    ]
}   

我试过了:

firstNameList=['arya', 'sansa','brandon']
import json
with open('/name.json', 'r+') as f:
    data = json.load(f)
    for item in firstNameList:
        Name['firstname']=item  
    f.seek(0)        #reset file position to the beginning.
    json.dump(data, f, indent=4)
    f.truncate()

以下应该可以解决问题:

import json 


with open('name.json', 'r+') as f:
    data = json.load(f)

    for name in firstNameList:
        data["Name"].append({"firstName": name, "lastName": "Stark"})

你可以试试这个:

import json
test = '''{
    "Name": [{
        "firstName": "John",
        "lastName": "Stark"
    }]
}'''
data  = json.loads(test)
firstNameList = ['Sansa','Arya','Brandon']
for member in firstNameList:
    test_dict = {'firstName': member, 'lastName': 'Stark'}
    data['Name'].append(test_dict)
dump = json.dumps(data)
print(dump)

这使用 json 库解析成字典,进行更改并转储回 json。
输出

{"Name": [{"firstName": "John", "lastName": "Stark"}, {"firstName": "Sansa", "lastName": "Stark"}, {"firstName": "Arya", "lastName": "Stark"}, {"firstName": "Brandon", "lastName": "Stark"}]}
dicts = {
    "Name": [{
            "firstName": "John",
            "lastName": "Stark"
        }
    ]
}

firstNameList = ['Sansa','Arya','Brandon']


for j in firstNameList:
    dicts["Name"].append({'firstName': j, 'lastName': 'Stark'})

print(dicts)

你会得到

{'Name': [{'firstName': 'John', 'lastName': 'Stark'}, {'firstName': 'Sansa', 'lastName': 'Stark'}, {'firstName': 'Arya', 'lastName': 'Stark'}, {'firstName': 'Brandon', 'lastName': 'Stark'}]}