代码之家  ›  专栏  ›  技术社区  ›  nad

在Python中访问字典对象转储中的项

  •  0
  • nad  · 技术社区  · 4 年前

    .json 文件,但其内部如下所示

    {"a":"aaa","b":"bbb","text":"hello"}
    {"a":"aaa","b":"bbb","text":"hi"}
    {"a":"aaa","b":"bbb","text":"hihi"}
    

    正如您所注意到的,这只是一堆字典对象。它既不是列表(也不是 [] 对象之间的逗号分隔符)或 JSON 虽然文件扩展名是 所以我真的很困惑如何阅读这个文件。

    text 每个字典对象的键。

    6 回复  |  直到 4 年前
        1
  •  2
  •   ewen-lbh    4 年前

    这个“奇怪的数据集”实际上是一种基于JSON的现有格式,称为 JSONL .

    正如@user655321所说,您可以解析每一行。下面是一个更完整的示例,完整的数据集可以在dict列表中找到 dataset :

    import json
    
    dataset = []
    with open("my_file.json") as file:
        for line in file:
            dataset.append(json.loads(line))
    
        2
  •  1
  •   bigbounty    4 年前
    In [51]: [json.loads(i)["text"] for i in open("file.json").readlines()]
    Out[51]: ['hello', 'hi', 'hihi']
    

    使用列表理解,更容易

        3
  •  1
  •   Kasper    4 年前

    您可以逐行读取它,并将这些行转换为JSON对象,并提取所需的数据 text 就你而言。

    import json
    lines = open("file.txt").readlines()
    for line in lines:
      dictionary = json.loads(line)
      print(dictionary["text"])
    
        4
  •  0
  •   user655321    4 年前

    由于它不是一个单一的JSON文件,您可以逐行读取输入并独立反序列化它们:

    import json
    with open('my_file.json') as fh:
       for line in fh:
          json_obj = json.loads(line)
          keys = json_obj.keys() # eg, 'a', 'b', 'text'
          text_val = json_obj['text'] # eg, 'hello', 'hi', or 'hihi'
    
        5
  •  0
  •   BroCannon    4 年前

    将内容拆分为 \n

    import json
    
    with open(your_file) as f:
        data = f.read()
    
    my_dicts = []
    for line in data.split():
        my_dicts.append(json.loads(line))
    
        6
  •  -1
  •   CHINTAN VADGAMA    4 年前
    import ast
    with open('my_file.json') as fh:
         for line in fh:
             try:
                 dict_data = ast.literal_eval(line)
                 assert isinstance(dict_data,dict)
                 ### Process Dictionary Data here or append to list to convert to list of dicts
             except (SyntaxError, ValueError, AssertionError):
                 print('ERROR - {} is not a dictionary'.format(line))