Python json.loads shows ValueError: Extra data

后端 未结 9 910
甜味超标
甜味超标 2020-11-22 16:21

I am getting some data from a JSON file \"new.json\", and I want to filter some data and store it into a new JSON file. Here is my code:

import json
with ope         


        
9条回答
  •  不知归路
    2020-11-22 16:55

    I think saving dicts in a list is not an ideal solution here proposed by @falsetru.

    Better way is, iterating through dicts and saving them to .json by adding a new line.

    our 2 dictionaries are

    d1 = {'a':1}
    
    d2 = {'b':2}
    

    you can write them to .json

    import json
    with open('sample.json','a') as sample:
        for dict in [d1,d2]:
            sample.write('{}\n'.format(json.dumps(dict)))
    

    and you can read json file without any issues

    with open('sample.json','r') as sample:
        for line in sample:
            line = json.loads(line.strip())
    

    simple and efficient

提交回复
热议问题