为了账号安全,请及时绑定邮箱和手机立即绑定

处理 Python 脚本中的索引位置以从 json 文件中删除 json 对象

处理 Python 脚本中的索引位置以从 json 文件中删除 json 对象

Smart猫小萌 2023-09-02 16:27:36
我有一个文件(my_file.json),其内容如下;[            {                "use":"abcd",                "contact":"xyz",                "name":"my_script.py",                "time":"11:22:33"             },            {                "use":"abcd"                "contact":"xyz",                "name":"some_other_script.py",                "time":"11:22:33"             },            {                "use":"apqwkndf",                "contact":"xyz",                "name":"my_script.py",                "time":"11:22:33"             },            {                "use":"kjdshfjkasd",                "contact":"xyz",                "name":"my_script.py",                "time":"11:22:33"             }]我使用以下 python 代码删除具有“name”的对象:“my_script.py”,#!/bin/usr/pythonimpoty jsonobj = json.load(open("my_file.json"))index_list = []for i in xrange(len(obj)):     if obj[i]["name"] == ["my_script.py"]      index_list.append(i)for x in range(len(index_list)):      obj.pop(index_list[x])open("output_my_file.json","w".write(json.dumps(obj, indent=4, separators=(',',': ')))但似乎我被卡住了,因为弹出索引后,实际 obj 中的索引位置发生了变化,这导致错误的索引删除或有时弹出索引超出范围。还有其他解决方案吗?
查看完整描述

5 回答

?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

尝试以相反的顺序弹出:

for x in reversed(range(len(index_list))):


查看完整回答
反对 回复 2023-09-02
?
PIPIONE

TA贡献1829条经验 获得超9个赞

import json

with open('my_file.json') as f:

    data = json.load(f)


data = [item for item in data if item.get('name') != 'my_script.py']


with open('output_my_file.json', 'w') as f:

    json.dump(data, f, indent=4)


查看完整回答
反对 回复 2023-09-02
?
猛跑小猪

TA贡献1858条经验 获得超8个赞

作为一般经验法则,您通常不想在迭代可迭代对象时对其进行更改。我建议你在第一个循环中保存你想要的元素:


import json


with open('path/to/file', 'r') as f:

    data = json.load(f)


items_to_keep = []

for item in data:

    if item['name'] != 'my_script.py':

        items_to_keep.append(item)


with open('path/to/file', 'w') as f:

    json.dump(items_to_keep, f, ...)

过滤可以简化为一行(称为列表理解)


import json


with open('path/to/file', 'r') as f:

    data = json.load(f)


items_to_keep = [item for item in data if item['name'] != 'my_script.py']


with open('path/to/file', 'w') as f:

    json.dump(items_to_keep, f, ...)


查看完整回答
反对 回复 2023-09-02
?
冉冉说

TA贡献1877条经验 获得超1个赞

尝试:


    import json


    json_file = json.load(open("file.json"))


    for json_dict in json_file:

        json_dict.pop("name",None)

    print(json.dumps(json_file, indent=4))

你不需要最后一行“json.dumps”,我只是把它放在那里,这样打印时看起来更易读。


查看完整回答
反对 回复 2023-09-02
?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

这将创建一个新列表,并仅将那些没有的列表分配"name": "my_script.py"到新列表中。

obj = [i for i in obj if i["name"] != "my_script.py"]


查看完整回答
反对 回复 2023-09-02
  • 5 回答
  • 0 关注
  • 164 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信