加载一个json文件,遍历它并在新文件中写入每个元素

时间:2018-05-18 04:17:42

标签: python json dictionary

我有一个json文件,现在我想修改json文件的(更改密钥)。我能够读取该文件中的每个项目,但不知道如何使用Python进行修改后在新词典中编写它

目前json文件是这样的:

[
  {"detail": ["Jishnu Prasad Rijal ", " Biratnagar , Morang,", "M", "BBS, India", "1"]},
  {"detail": ["Lakshmishwar Prasad ", " Kharihani , Dhanusa,", "M", "BBS, India", "2"]},
]

但我希望这种格式:

[{
  "name":"Jishnu Prasad Rijal","roll_no":1,"gender":"Male",
  "address":"Biratnagar,Morang","degree":"BBS, India"
}, {
  "name":"Lakshmishwar Prasad ","roll_no":2,"gender":"Male",
  "address":"Kharihani , Dhanusa","degree":"BBS, India"
}]

非常感谢帮助。 谢谢

2 个答案:

答案 0 :(得分:3)

只需使用 zip

即可
keys = ['name', 'address', 'gender', 'degree', 'role_no']
x = [dict(zip(keys, i['detail'])) for i in x]

[{'name': 'Jishnu Prasad Rijal ', 'address': ' Biratnagar , Morang,', 'gender': 'M', 'degree': 'BBS, India', 'role_no': '1'}, {'name': 'Lakshmishwar Prasad ', 'address': ' Kharihani , Dhanusa,', 'gender': 'M', 'degree': 'BBS, India', 'role_no': '2'}]

答案 1 :(得分:0)

input_dict = [
        {"detail": ["Jishnu Prasad Rijal ", " Biratnagar , Morang,", "M", "BBS, India", "1"]},
        {"detail": ["Lakshmishwar Prasad ", " Kharihani , Dhanusa,", "M", "BBS, India", "2"]},
        ]
cols = ['name','address','gender','degree','roll_no']
output_list = []
for el in input_dict:
            x = el['detail']
            #print(dict(zip(cols,x)))
            op = dict(zip(cols,x))
            output_list.append(op)
print(output_list)