[英]how to remove key/value pair in a json file in python
{
"duncan_long": {
"id": "drekaner",
"name": "Duncan Long",
"favorite_color": "Blue"
},
"kelsea_head": {
"id": "wagshark",
"name": "Kelsea Head",
"favorite_color": "Ping"
},
"phoenix_knox": {
"id": "jikininer",
"name": "Phoenix Knox",
"favorite_color": "Green"
},
"adina_norton": {
"id": "slimewagner",
"name": "Adina Norton",
"favorite_color": "Red"
}
}
I am trying to Return a JSON list of all the users excluding the id of the user我正在尝试返回除用户 ID 之外的所有用户的 JSON 列表
Assuming your the file in which you have your JSON is called file.json
:假设您拥有 JSON 的文件称为
file.json
:
import json
with open('file.json') as f:
d = json.loads(f)
for key, value in d.items():
del value['id']
d[key] = value
Alternative you can use the following:或者,您可以使用以下内容:
import json
with open('file.json') as f:
d = json.loads(f)
for key, value in d.items():
value.pop('id', None) // this will not crash if the element has no key 'id'
import json
with open('file.json') as fin:
your_structure = json.load(fin)
for value in your_structure.values():
value.pop('id', None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.