【问题标题】:Access multiple dictionaries in a file - Python访问文件中的多个字典 - Python
【发布时间】:2018-02-16 19:30:27
【问题描述】:

我对 Json 文件非常陌生。我有一个包含多个 json 对象的 json 文件,如下所示:

{"ID":"12345","Timestamp":"20140101", "Usefulness":"Yes",
  "Code":[{"event1":"A","result":"1"},…]}
{"ID":"1A35B","Timestamp":"20140102", "Usefulness":"No",
  "Code":[{"event1":"B","result":"1"},…]}
{"ID":"AA356","Timestamp":"20140103", "Usefulness":"No",
  "Code":[{"event1":"B","result":"0"},…]}
…

我想像流一样解析这些 json 对象。然而,对我来说最终的游戏是创建 event1 和 result 的成对组合。像这样:

[AB, AB, BB],[11,10,10]

我知道的: dict的确切结构

我不知道的事情:如何通过dict提取这些dict来执行这个操作。

我无法修改现有文件,所以不要告诉我添加'[ ]和','

其他帮助:

我可能会遇到无法直接存储在内存中的文件,因此更适合使用 解决方案。

【问题讨论】:

    标签: json python-3.x dictionary stream


    【解决方案1】:

    最简单的方法是将文件流输入自定义生成器,该生成器将“预解析”json 对象。这可以通过一些状态变量来完成,有点天真地计算打开的 {[ 的数量 - 每次达到零时,它都会产生一个带有完整 JSON 对象的字符串。

    我无法从您提供的示例中找出您想要的最终意图。我想你在“代码”中有其他字典,最后你想要的是最外层字典的每个“代码”值内的一对组合“event1,结果”。如果不是这样,适合自己改代码。

    (有序的 dict 足以存储您需要的结果 - 如果需要,您可以检索单独的键和值列表)

    from collections import OrderedDict
    import json
    import string
    import sys
    
    def char_streamer(stream):
        for line in stream:
            for char in line:
                yield char
    
    def json_source(stream):
        result = []
        curly_count = 0
        bracket_count = 0
        nonwhitespace_count = 0
        inside_string = False
        previous_is_escape = False
        for char in char_streamer(stream):
            if not result and char in string.whitespace:
                continue
            result.append(char)
    
            if char == '"':
                if inside_string:
                    inside_string = True
                elif not previous_is_escape:
                    inside_string = False
    
            if inside_string:
                if char == "\\": # single '\' character
                    previous_is_escape = not previous_is_escape
                else:
                    previous_is_escape = False
    
                continue
    
            if char == "{":
                curly_count += 1
            if char == "[":
                bracket_count += 1
    
            if char == "}":
                curly_count -= 1
            if char == "]":
                bracket_count -= 1
    
            if curly_count == 0 and bracket_count== 0 and result:
                yield(json.loads("".join(result)))
                result = []
    
    
    
    
    def main(filename):
        result = OrderedDict()
        with open(filename) as file:
            for data_part in json_source(file):
                # agregate your data here
    
        print (result.keys(), result.values())
    
    main(sys.argv[1])
    

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      相关资源
      最近更新 更多