【问题标题】:Python - json.loads large file of dictionaries that are not connectedPython - json.loads 未连接的大字典文件
【发布时间】:2020-12-04 18:43:30
【问题描述】:

我有一个大(50,000 多行)文件,它是来自另一个应用程序的 json 输出的集合,我想以 json 格式读取并执行一些分析。问题是,虽然单个条目是有效的 json,但我无法以 json 格式读取整个文件,因为每个条目都没有连接。

片段:

{"action":"Iops","idg":"2214472975167211","idx":537994,"system":"Qos","utc":"2019-07-02T11:45:09.606765Z","ver":"1.1","xQosIops":{"ActualReadOps":{"avg":0,"ct":60,"max":0,"min":0,"std":0,"tmax":29880,"tmin":29880}}}
{"action":"Latency","idg":"2214472975167211","idx":537995,"system":"Qos","utc":"2019-07-02T11:45:09.606829Z","ver":"1.1","xQosLatency":{"AverageLocalWriteLatencyUS":{"avg":0,"ct":60,"max":0,"min":0,"std":0,"tmax":29880,"tmin":29880}}}

单独它们都是有效的,但我想要实现的是动态地将所有这些连接到一个 json 对象中。需要注意的是,这些 json 响应可能跨越多行,所以我不能只逐行阅读。任何帮助将不胜感激。

【问题讨论】:

    标签: python json parsing


    【解决方案1】:

    您可以使用普通 Python 加载文件的内容(不使用 json 包),然后使用 json 解析每一行。

    例子:

    import json
    
    data_fp = "/path/to/data.txt"
    
    with open(data_fp, "r") as f:
        lines = f.readlines()
    
    # now, parse each line as a JSON string
    json_object = [json.loads(l) for l in line]
    
    # optional: dump as a JSON file
    with open("/path/to/output.json", "w") as f:
        json.dump(json_object, f)
    

    编辑:如果每个字典不一定限于一行,您可以尝试解析 JSON 的可变行数,直到它成功(继续上面的示例):

    start_line = 0
    end_line = 1
    json_object = []
    while end_line <= len(lines):
        try:
            data = json.loads("".join(lines[start_line:end_line]))
        except:
            end_line += 1
        else:
            json_object.append(data)
            start_line = end_line
            end_line = start_line + 1
    

    【讨论】:

    • 但是输出可以跨越多行。
    【解决方案2】:

    如果每一行都是有效的 JSON,您可以将其包装在一个单独读取它们的脚本中,并将它们附加到一个列表中。比如:

    import json
    
    data = []
    
    with open("fakejson.txt") as data_f:
        for line in data_f:
            data.append(json.loads(line)
    

    【讨论】:

    • 每一行不一定是一个新条目,不幸的是单个输出可能跨越多行。
    • 您可能需要遍历文件,使用堆栈来匹配左大括号和右大括号和字符串({}[]"")以识别唯一有效的 json对象。类似stackoverflow.com/questions/29991917/…
    【解决方案3】:

    您可以通过查找开-关 {} 对来创建识别 json 的函数。见下文:

    def isjson(t):
        for i in range(len(t)):
            if t[i]=='{':
                s=t[i]
                c=1
                n=1
                while c>0:
                    s+=t[i+n]
                    if t[i+n]=='{':
                        c+=1
                    elif t[i+n]=='}':
                        c-=1
                    n+=1
                return (s, i+n)
    

    您现在可以使用以下内容将整个文件加载为文本:

    with open('yourfile.txt') as f:
        t=f.read()
    

    然后提取所有的json,使用上面的函数:

    d={}
    
    n=1
    while True:
       d[n]=isjson(t)[0]
       t=t[isjson(t)[1]+1:]
       n+=1
       if t.count('{')==0:
           break
            
    

    【讨论】:

      猜你喜欢
      • 2013-05-07
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 2021-07-20
      • 2017-10-18
      • 2020-12-09
      相关资源
      最近更新 更多