如何用python正确删除json中的数据

2024-06-08 16:45:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的json如下所示:

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

Tags: 数据方法用户脚本jsonnumber目标example
1条回答
网友
1楼 · 发布于 2024-06-08 16:45:07

您可以将json转换为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": {}}'

相关问题 更多 >