繁体   English   中英

如何在 python 的 json 文件中删除键/值对

[英]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"
    }
}

我正在尝试返回除用户 ID 之外的所有用户的 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

或者,您可以使用以下内容:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM