修改json-使用python删除json结构中的某些元素

修改json-使用python删除json结构中的某些元素,python,json,Python,Json,我的json结构如下: "AGENT": { "pending": [], "active": null, "completed": [ **{ "result": { "job1.AGENT": "SUCCESS", "job2.AGENT": "SUCCESS" }, "return_value": {

我的json结构如下:

"AGENT": {
    "pending": [],
    "active": null,
    "completed": [
        **{
            "result": {
                "job1.AGENT": "SUCCESS",
                "job2.AGENT": "SUCCESS"
            },
            "return_value": {
                "job1.AGENT": "",
                "job2.AGENT": ""
            },
            "visible": true,
            "global": true,
            "locale": [
                "en_US"
            ],
            "complete_time": "2018-01-24T17:44:33.484Z",
            "persist": true,
            "type": "script",
            "script": "<script_name>.py",
            "preset_status": "CONFIGURING",
             "parameters": {},
            "submit_time": "2018-01-24T17:44:26.747Z"
        }**,
        {
            "result": {
                ..
            },
            "return_value": {
                ..
            },
            "visible": true,
            "global": true,
            "locale": [
                "en_US"
            ],
            "complete_time": "2018-04-2T17:44:40.049Z",
             "submit_time": "2018-04-2T17:44:26.817Z"
        }

这会打印完整的时间。然而,我的问题是“AGENT”不是一个常量字符串。字符串可以变化。此外,我还需要根据完整的时间找出删除整个json块的逻辑。好的,我假设您能够正确地将json加载到Python字典中,让我们称之为
item_dict
,但键可能会有所不同

现在,您需要它来进入Python对象,并解码
complete\u time
字段。不幸的是,Python
strtime
不知道
Z
时区,因此我们必须跳过最后一个字符

此外,在迭代集合对象时不应修改它,因此最有效的方法是存储要删除的索引,然后再删除它们。代码可以是:

datelimit = datetime.datetime(2018, 4, 1)       # limit date for completed_time
to_remove = []
dateformat = '%Y-%m-%dT%H:%M:%S.%f'
for k, v in item_dict.items():                  # enumerate top_level objects
    for i, block in enumerate(v['completed']):  # enumerate inner blocks
        complete_time = datetime.datetime.strptime(   # skip last char from complete_time
            block["complete_time"][:-1], dateformat)
        # print(k, i, complete_time)              # uncomment for tests
        if complete_time < datelimit:           # too old
            to_remove.append((k, i))            # store the index for later processing

for k, i in reversed(to_remove):           # start from the end to keep consistent indices
    del item_dict[k]["completed"][i]       # actual deletion
datelimit=datetime.datetime(2018,4,1)#完成时间的限制日期
删除=[]
日期格式=“%Y-%m-%dT%H:%m:%S.%f”
对于项目_dict.items()中的k,v:#枚举顶级对象
对于i,枚举中的块(v['completed']):#枚举内部块
complete_time=datetime.datetime.strtime(#跳过complete_time的最后一个字符
块[“完成时间”][:-1],日期格式)
#打印(k,i,完成时间)#取消对测试的注释
如果完成时间<日期限制:#太旧
to_remove.append((k,i))#存储索引以供以后处理
对于k,i in reversed(to_remove):#从末尾开始以保持索引一致
删除项目_dict[k][“已完成”][i]#实际删除

您尝试过什么?(你应该再读一遍……)我不知道该怎么办。首先,我需要至少看看我是否可以正确打印“完整时间”…即AGENT.completed.complete\u time我尝试了以下方法:json\u data=json.dumps(data)item\u dict=json.load(data)print item\u dict[“AGENT”][“completed”][0][“complete\u time”]这会打印完整时间。然而,我的问题是“AGENT”不是一个常量字符串。字符串可以变化。此外,我还需要根据完整的时间找出删除整个json块的逻辑。这段代码应该在问题中,注释中的代码很难阅读……感谢serge的帮助和指导,我能够让这段代码片段正常工作,解决了我的问题。我还对问题进行了编辑,以包括我正在将json数据加载到字典中的代码片段,以便按照您的建议为其他用户提供更好的可读性。嗨,Serge,我如何处理缩放?如果我的json非常大(>1GB),因此我必须通过将json分解成块来执行类似的操作,该怎么办?问题是我不能分解成任意块,因为这只会破坏json格式。
datelimit = datetime.datetime(2018, 4, 1)       # limit date for completed_time
to_remove = []
dateformat = '%Y-%m-%dT%H:%M:%S.%f'
for k, v in item_dict.items():                  # enumerate top_level objects
    for i, block in enumerate(v['completed']):  # enumerate inner blocks
        complete_time = datetime.datetime.strptime(   # skip last char from complete_time
            block["complete_time"][:-1], dateformat)
        # print(k, i, complete_time)              # uncomment for tests
        if complete_time < datelimit:           # too old
            to_remove.append((k, i))            # store the index for later processing

for k, i in reversed(to_remove):           # start from the end to keep consistent indices
    del item_dict[k]["completed"][i]       # actual deletion