简体   繁体   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"
    }
}

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.

相关问题 如何在python字典中删除键/值对? - How to remove a key/value pair in python dictionary? 如何使用python替换json文件中的键的键值对 - how to replace a key-value pair for a key in json file using python 如何使用python将具有键值对的已抓取json数据保存为json文件格式 - How to save scraped json data with key value pair into a json file format using python 使用python在文件中合并具有相同键值对的json对象 - Merge the json objects with same key value pair in a file using python 如何从Python中删除yaml转储中的键/值对? - How to remove a key/value pair from yaml dump, in Python? 如何将 python 字典的每个键值对存储在 json 文件中的单独行上? - How can I store each key-value pair of my python dictionary on a separate line in json file? 如何使用 CSV 文件将列转换为 json 以使键和值对来自使用 CSV 的不同列? - How to convert columns from CSV file to json such that key and value pair are from different columns of the CSV using python? 如何使用python从一个大的json文件中找出特定的键值对 - How to find out specific key-value pair from a big json file using python 如何将键:值对添加到简单的 JSON 文件 - How can I add key: value pair to simple JSON file 如何使用json文件形成带有键值对的字典 - how to form a dictionary with key-value pair using a json file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM