删除json响应python中的某些部分

2024-04-26 05:19:34 发布

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

这是我的JSON响应,我想删除整个meta头部分。你知道吗

{
    "meta": {
        "limit": 1000,
        "next": "https://cisco-demo.obsrvbl.com/api/v3/observations/all/?limit=1000&offset=1000",
        "offset": 0,
        "previous": null,
        "total_count": 1863020
    },
    "objects": [
        {
            "creation_time": null,
            "end_time": "2017-08-17T19:40:00Z",
            "id": 281,
            "observation_name": "External Port Scanner",
            "port_count": 251,
            "port_ranges": "0-1023",
            "resource_name": "port_scanner_external_v1",
            "scan_type": "inbound",
            "scanned_ip": "209.182.184.2",
            "scanned_ip_country_code": "US",
            "scanned_packets": 999,
            "scanner_ip": "130.126.24.53",
            "scanner_ip_country_code": "US",
            "scanner_packets": 997,
            "source": 109,
            "time": "2017-08-17T19:40:00Z"
        },
        {
            "creation_time": null,
            "end_time": "2017-08-17T19:50:00Z",
            "id": 304,
            "observation_name": "External Port Scanner",
            "port_count": 41,
            "port_ranges": "0-1023",
            "resource_name": "port_scanner_external_v1",
            "scan_type": "inbound",
            "scanned_ip": "209.182.184.2",
            "scanned_ip_country_code": "US",
            "scanned_packets": 152,
            "scanner_ip": "130.126.24.53",
            "scanner_ip_country_code": "US",
            "scanner_packets": 152,
            "source": 109,
            "time": "2017-08-17T19:50:00Z"
        },

Tags: nameiptimeportcountcodecountrynull
1条回答
网友
1楼 · 发布于 2024-04-26 05:19:34
import json

with open('myfile.txt') as fp:
    my_dict = json.loads(fp.read())

try:
    del my_dict['meta']
except KeyError:
    pass

我假设您已经有了JSON作为字典,在上面的代码中,我只是从一个文本文件加载它。您要查找的命令是del。最好将它放在try/catch块中,以防处理的字典没有meta字段,因为在这种情况下,它会抛出KeyError并中断。你知道吗

相关问题 更多 >