如何使用Python将json文件中的数据拆分为两个json文件



我有一个json文件,有两组数据,我想把这个json文件分成两个单独的json文件,这样每个文件都有一组数据。例如,现有的json文件如下所示:

{ 
"client_id" : {"0": "abc123", "1": "def456"},
"client_name": {"0": "companyA", "1": "companyB"},
"revenue": {"0": "54,786", "1": "62,754"},
"rate" : {"0": "4", "1": "5"}
}

我正在尝试为条目"0"创建两个单独的json文件和"1";这样的。

文件1

{ 
"client_id" : "abc123",
"client_name": "companyA",
"revenue": "54,786", 
"rate" : "4"
}

文件2

{ 
"client_id" :  "def456",
"client_name": "companyB",
"revenue":  "62,754",
"rate" :  "5"
}

我尝试使用for循环来做这个,但不能使它工作。有人知道如何在Python中拆分json文件吗?

您可以尝试:

import json
dct = {
"client_id": {"0": "abc123", "1": "def456"},
"client_name": {"0": "companyA", "1": "companyB"},
"revenue": {"0": "54,786", "1": "62,754"},
"rate": {"0": "4", "1": "5"},
}
tmp = {}
for k, v in dct.items():
for kk, vv in v.items():
tmp.setdefault(kk, {}).update({k: vv})
for i, v in enumerate(tmp.values(), 1):
with open(f"File{i}.json", "w") as f_out:
json.dump(v, f_out, indent=4)

创建两个文件File1.json,File2.json:

{
"client_id": "abc123",
"client_name": "companyA",
"revenue": "54,786",
"rate": "4"
}

{
"client_id": "abc123",
"client_name": "companyA",
"revenue": "54,786",
"rate": "4"
}

编辑:创建输出字典:

dct = {
"client_id": {"0": "abc123", "1": "def456"},
"client_name": {"0": "companyA", "1": "companyB"},
"revenue": {"0": "54,786", "1": "62,754"},
"rate": {"0": "4", "1": "5"},
}
tmp = {}
for k, v in dct.items():
for kk, vv in v.items():
tmp.setdefault(kk, {}).update({k: vv})
out = {}
for i, v in enumerate(tmp.values(), 1):
out[f"File{i}"] = v
print(out)

打印:

{
"File1": {
"client_id": "abc123",
"client_name": "companyA",
"revenue": "54,786",
"rate": "4",
},
"File2": {
"client_id": "def456",
"client_name": "companyB",
"revenue": "62,754",
"rate": "5",
},
}

您可以使用json包读取json文件并在for循环中处理它

import json
with open('json_data.json') as json_file:
data = json.load(json_file)
# Contains the "0", "1", ...
list_of_new_dicts = data["client_id"].keys()
new_data = {}
for key, dico in data.items():
for num, value in dico.items():
new_data[num][key] = value

您的新数据字典应该如下所示:

{
"0":{
"client_id" : "abc123",
"client_name": "companyA",
"revenue": "54,786", 
"rate" : "4"
},
"1":{ 
"client_id" :  "def456",
"client_name": "companyB",
"revenue":  "62,754",
"rate" :  "5"
}
}

然后保存文件,你可以这样做:

with open('json_data_0.json', 'w') as outfile:
json.dump(new_data["0"], outfile)

最新更新