【问题标题】:Delete some parts in json response python删除json响应python中的一些部分
【发布时间】:2019-08-08 14:30:32
【问题描述】:

这是我的 JSON 响应,我想删除整个元标题部分。

{
    "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"
        },

【问题讨论】:

  • 欢迎使用 stackoverflow。你试过什么?你得到什么错误?你试过 python JSON 模块吗?您可以遵循的方向是:将您的 json 转换为 python 对象,删除您不需要的部分并将其转换回 json

标签: python json api parsing http-delete


【解决方案1】:
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 块中是个好主意,以防万一您正在处理没有元字段的字典,因为在这种情况下,它会抛出 KeyError 并中断。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    相关资源
    最近更新 更多