【问题标题】:Need to cut off some unnecessary information from a JSON file and preserve the JSON structure需要从 JSON 文件中截取一些不必要的信息并保留 JSON 结构
【发布时间】:2020-08-28 00:14:09
【问题描述】:

我有一个 JSON 文件

[
    {
        "api_key": "123123112313121321",
        "collaborators_count": 1,
        "created_at": "",
        "custom_event_fields_used": 0,
        "discarded_app_versions": [],
        "discarded_errors": [],
        "errors_url": "https://api.bugsnag.com/projects/1231231231312/errors",
        "events_url": "https://api.bugsnag.com/projects/1231231231213/events",
        "global_grouping": [],
        "html_url": "https://app.bugsnag.com/lol/kek/",
        "id": "34234243224224",
        "ignore_old_browsers": true,
        "ignored_browser_versions": {},
        "is_full_view": true,
        "language": "javascript",
        "location_grouping": [],
        "name": "asdasdaasd",
        "open_error_count": 3,
        "release_stages": [
            "production"
        ],
        "resolve_on_deploy": false,
        "slug": "wqeqweqwwqweq",
        "type": "js",
        "updated_at": "2020-04-06T15:22:10.480Z",
        "url": "https://api.bugsnag.com/projects/12312312213123",
        "url_whitelist": null
    }
]

我需要删除除“id:”和“name:”之外的所有行并保留 JSON 结构。任何人都可以建议使用 Python 或 bash 脚本来处理这个问题吗?

【问题讨论】:

  • 在加载 json 之后会像 dictionary 所以只需删除你不需要的其他密钥 dict.pop('key', None)del dict["key"]

标签: python json python-3.x bash jq


【解决方案1】:

将您的 JSON 转换为 Pandas 数据框

{  

import pandas as pd 
df=pd.read_json('your json variable')
res=df.drop(['url_whitelis','api_key'],axis=1) 
                                          
pd.to_json(res) }    

【讨论】:

  • 没有必要使用 pandas 来删除 json 键
【解决方案2】:

使用python,你可以先用json.load反序列化JSON文件(对象的JSON数组),然后用列表解析过滤掉你想要的键:

from json import load

keys = ["name", "id"]

with open("test.json") as json_file:
    data = load(json_file)

    filtered_json = [{k: obj.get(k) for k in keys} for obj in data]

    print(filtered_json)

输出:

[{'name': 'asdasdaasd', 'id': '34234243224224'}]

如果我们想将这个python列表序列化到另一个输出文件,我们可以使用json.dump

from json import load
from json import dump

keys = ["name", "id"]

with open("test.json") as json_file, open("output.json", mode="w") as json_output:
    data = load(json_file)

    filtered_json = [{k: obj.get(k) for k in keys} for obj in data]

    dump(filtered_json, json_output, indent=4, sort_keys=True)

output.json

[
    {
        "id": "34234243224224",
        "name": "asdasdaasd"
    }
]

【讨论】:

    【解决方案3】:

    jq:

    $ jq 'map({id: .id, name: .name})' input.json 
    [
      {
        "id": "34234243224224",
        "name": "asdasdaasd"
      }
    ]
    

    【讨论】:

    • 啊,这是一个方便的命令行工具。我不得不承认我以前从未使用过它。它使用什么查询语言?它看起来类似于 JMESPath,但不完全一样。
    • @RoadRunner jq 使用自己的 DSL 来操作 JSON。见stedolan.github.io/jq/manual
    • @RoadRunner,您可能还喜欢jtc(谷歌上jtcjson - 我之前创建的也是非常强大的JSON 处理器),使用jtc 的解决方案看起来像:@ 987654328@
    • 更简单:jq 'map({id, name})' input.json
    【解决方案4】:

    你可以试试这个:

    import json
    
    with open('<input filename>', 'r') as f:
        data = json.load(f)
    
    new_data = []
    for item in data:
        new_item = {key: value for key, value in item.items() if key == "id" or key =="name"}
        new_data.append(new_item)
    
    with open('<output filename>', 'w') as f:
        json.dump(new_data, f)
    

    【讨论】:

      猜你喜欢
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 2011-09-07
      • 1970-01-01
      相关资源
      最近更新 更多