create valid json object in python

后端 未结 2 646
梦如初夏
梦如初夏 2021-01-27 15:51

Each line is valid JSON, but I need the file as a whole to be valid JSON.

I have some data which is aggregated from a web service and dumped to a file, so it\'s JSON-ea

相关标签:
2条回答
  • 2021-01-27 16:24

    Each line looks like a valid JSON document.

    That's "JSON Lines" format (http://jsonlines.org/)

    Try to process each line independantly (json.loads(line)) or use a specialized library (https://jsonlines.readthedocs.io/en/latest/).

    def process(oneline):
        # do what you want with each line
        print(oneline['record'])
    
    with open('toy_two.json', 'rb') as inpt:
        for line in inpt:
            process(json.loads(line))
    
    0 讨论(0)
  • 2021-01-27 16:32

    This looks like NDJSON that I've been working with recently. The specification is here and I'm not sure of its usefulness. Does the following work?

    with open('the file.json', 'rb') as infile:
        data = infile.readlines()
        data = [json.loads(item.replace('\n', '')) for item in data] 
    

    This should give you a list of dictionaries.

    0 讨论(0)
提交回复
热议问题