Python json.loads shows ValueError: Extra data

后端 未结 9 810
甜味超标
甜味超标 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:52

    If you want to solve it in a two-liner you can do it like this:

    with open('data.json') as f:
        data = [json.loads(line) for line in f]
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 16:58

    Well , it might help someone. i just got the same error while my json file is like this

    {"id":"1101010","city_id":"1101","name":"TEUPAH SELATAN"}
    {"id":"1101020","city_id":"1101","name":"SIMEULUE TIMUR"}
    

    and i found it malformed, so i changed it into somekind of

    {
      "datas":[
        {"id":"1101010","city_id":"1101","name":"TEUPAH SELATAN"},
        {"id":"1101020","city_id":"1101","name":"SIMEULUE TIMUR"}
      ]
    }
    
    0 讨论(0)
提交回复
热议问题