簡體   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