首页 > 解决方案 > 如何使用python从json中正确删除数据

问题描述

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

我的 json 看起来像这样:

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

标签: pythonjsonpython-2.7

解决方案


您可以将 json 转为 a dict,操作dict,然后将其转回 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": {}}'

推荐阅读