Loading and parsing a JSON file with multiple JSON objects

前端 未结 3 1635
醉话见心
醉话见心 2020-11-22 09:40

I am trying to load and parse a JSON file in Python. But I\'m stuck trying to load the file:

import json
json_data = open(\'file\')
data = json.load(json_dat         


        
3条回答
  •  悲哀的现实
    2020-11-22 10:12

    You have a JSON Lines format text file. You need to parse your file line by line:

    import json
    
    data = []
    with open('file') as f:
        for line in f:
            data.append(json.loads(line))
    

    Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.

    Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.

    If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.

提交回复
热议问题