如何使用python从json中正确删除数据 [英] How to properly delete data from json with python

查看:580
本文介绍了如何使用python从json中正确删除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到使用 python 删除 json 数据的正确方法.我使用 python 脚本的目标是删除用户输入的联系人.我想删除他们的电子邮件、电话号码和姓名,但保留我的其余联系人.

Im trying to find the proper way to delete json data with python. My goal with the python script is to remove the contact that the user inputs. I want to remove their email, number, and name but keep the rest of my contacts.

我的 json 看起来像这样:

My json looks like this:

{
    "contacts": {
        "example_contact": {
            "email": "email@domain.com",
            "number": "phone number"
        }
    }
}

推荐答案

你可以把json转成dict,操作dict,再转回json.

You can turn the json to a dict, manipulate the dict, and turn it back to json.

In [244]: json_string = """{
     ...:     "contacts": {
     ...:         "example_contact": {
     ...:             "email": "email@domain.com",
     ...:             "number": "phone number"
     ...:         }
     ...:     }
     ...: }"""

In [250]: contacts = json.loads(json_string)

In [251]: del contacts['contacts']['example_contact']

In [252]: contacts
Out[252]: {'contacts': {}}

In [253]: json.dumps(contacts)
Out[253]: '{"contacts": {}}'

这篇关于如何使用python从json中正确删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆