python - 如何使用python从json中正确删除数据
问题描述
我试图找到用python删除json数据的正确方法。我使用 python 脚本的目标是删除用户输入的联系人。我想删除他们的电子邮件、电话号码和姓名,但保留我的其他联系人。
我的 json 看起来像这样:
{
"contacts": {
"example_contact": {
"email": "email@domain.com",
"number": "phone number"
}
}
}
解决方案
您可以将 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": {}}'
推荐阅读
- java - 有没有什么简单的方法可以在按下特定按钮后重新运行方法/程序?
- javascript - 将变量内插为组件模板的内联样式参数?
- pandas - 高效的 Dataframe 列(对象)到 DateTime 的转换
- gitlab-ci - 如何使用 lftp 删除除 cgi-bin 和 .ftpquota 之外的所有文件
- docker - CRIT Supervisor 以 root 身份运行(配置文件中没有用户)_将 sameersbn/gitlab 升级到最新版本
- firebase - 不能在颤动的火力基地中一起使用 Where 和 orderBy
- python - pyomo - 将权力包含在约束表达式中的困难
- linux - 您将如何设计一个系统来保护 Linux 中的日志信息?
- java - Android 中的 Firestore 查询行为异常
- java - 线程“主”java.util.zip.ZipException 中的异常:打开 zip 文件时出错