【问题标题】:How to merge non-fixed key json multilines into one json abstractly如何抽象地将非固定键json多行合并为一个json
【发布时间】:2022-12-24 22:23:16
【问题描述】:

如果我有一个像这样的 30m 条目的重 json 文件

{"id":3,"price":"231","type":"Y","location":"NY"}
{"id":4,"price":"321","type":"N","city":"BR"}
{"id":5,"price":"354","type":"Y","city":"XE","location":"CP"}
--snip--
{"id":30373779,"price":"121","type":"N","city":"SR","location":"IU"}
{"id":30373780,"price":"432","type":"Y","location":"TB"}
{"id":30373780,"price":"562","type":"N","city":"CQ"}

我如何只能抽象位置和城市并将其解析为一个像 python 中那样的 json:

{
    "orders":{
        3:{
            "location":"NY"
        },
        4:{
            "city":"BR"
        },
        5:{
            "city":"XE",
            "location":"CP"
        },
        30373779:{
            "city":"SR",
            "location":"IU"
        },
        30373780:{
            "location":"TB"
        },
        30373780:{
            "city":"CQ"
        }
    }
}

P.S:美化语法不是必需的。

【问题讨论】:

  • 让我们首先指出这(输入)不是json,而是看起来像ndjson/jsonlines格式(即您需要单独读取/解析每一行或为此使用说服库)。然后,询问您到目前为止的代码 (minimal reproducible example) 以及您的代码有什么具体问题。

标签: python json parsing


【解决方案1】:

假设您的输入文件实际上是 jsonlines 格式,那么您可以读取每一行,从字典中提取 citylocation 键,然后将它们附加到新字典:

import json
from collections import defaultdict

orders = { 'orders' : defaultdict(dict) }
with open('orders.txt', 'r') as f:
    for line in f:
        o = json.loads(line)
        id = o['id']
        if 'location' in o:
            orders['orders'][id]['location'] = o['location'] 
        if 'city' in o:
            orders['orders'][id]['city'] = o['city'] 

print(orders)

示例数据的输出(请注意它有两个 30373780 id 值,因此这些值会合并到一个字典中):

{
    "orders": {
        "3": {
            "location": "NY"
        },
        "4": {
            "city": "BR"
        },
        "5": {
            "location": "CP",
            "city": "XE"
        },
        "30373779": {
            "location": "IU",
            "city": "SR"
        },
        "30373780": {
            "location": "TB",
            "city": "CQ"
        }
    }
}

【讨论】:

    【解决方案2】:

    正如您所说的那样,您的文件非常大,您可能不想将所有条目都保存在内存中,这是逐行使用源文件并立即写入输出的方法:

    import json
    
    with open(r"in.jsonp") as i_f, open(r"out.json", "w") as o_f:
        o_f.write('{"orders":{')
        for i in i_f:
            i_obj = json.loads(i)
            o_f.write(f'{i_obj["id"]}:')
            o_obj = {}
            if location := i_obj.get("location"):
                o_obj["location"] = location
            if city := i_obj.get("city"):
                o_obj["city"] = city
            json.dump(o_obj, o_f)
            o_f.write(",")
        o_f.write('}}')
    

    它将以您在问题中提供的相同格式生成半有效的 JSON 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-30
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多