如何将JSON内容传递到另一个JSON文件



file1.json

[
{
"username": "Jack"
},
{
"username": "Harry"
}
]

我只想获取用户名[‘Jack’,‘Harry’],并使用python替换其他json文件。

file2.json

{
"profile":
[
{
"custom_data": 
{
"env.user_data": "fetch_name"
}
}
]
}

因此,作为file2.json"env.user_data": ['Jack', 'Harry']中的最终输出

下面是我用来读取文件的代码。

import json
def name():
contents= []
try:
with open("file1.json", 'r') as f:
contents = json.load(f)
except Exception as e:
print(e)
data = [item.get('username') for item in contents]
return data   
test=name()
print(test)

不清楚当有多个profile元素时会发生什么(难道每个用户都不应该有自己的配置文件吗?)

但如果你只想更换一个元素,那么它看起来就像这个

import json 
with open('file1.json') as f1, open('file2.json') as f2:
j1 = json.load(f1)
j2 = json.load(f2)
names = [d['username'] for d in j1]
j2['profile'][0]['custom_data']['env.user_data'] = names
with open('file2.json', 'w') as f:
json.dump(j2, f)

最新更新