Can't parse json file: json.decoder.JSONDecodeError: Extra data.

后端 未结 3 737
走了就别回头了
走了就别回头了 2020-12-20 03:56

I have a json file. A simplified version of it looks as following:

{
  \"host\": \"a.com\",
  \"ip\": \"1.2.2.3\",
  \"port\": 8
}
{
  \"host\":         


        
相关标签:
3条回答
  • 2020-12-20 04:28

    Your JSON file isn't available in proper format.
    It should be like this, inside a list, comma separated:

    [
        {
         "host": "a.com",
         "ip": "1.2.2.3",
         "port": 8
        },
        {
         "host": "b.com",
         "ip": "2.5.0.4",
         "port": 3
    
        },
        {
         "host": "c.com",
         "ip": "9.17.6.7",
         "port": 4
        },
    ]
    
    0 讨论(0)
  • 2020-12-20 04:32

    As you already found out: that is not valid JSON.
    You have to modify it to make it valid, specifically, you have to wrap your top-level objects in an array. Try this:

    import json
    from pprint import pprint
    
    with open('myfile.json') as f:
        data = json.loads("[" + 
            f.read().replace("}\n{", "},\n{") + 
        "]")
    
        print(data)
    
    0 讨论(0)
  • 2020-12-20 04:43

    Your JSON data set is not valid , You can merge them into one array of objects. For example :

    [
        {
            "host": "a.com",
            "ip": "1.2.2.3",
            "port": 8
        }, {
            "host": "b.com",
            "ip": "2.5.0.4",
            "port": 3
    
        }, {
            "host": "c.com",
            "ip": "9.17.6.7",
            "port": 4
        }
    ]
    

    In JSON you can't have multiple objects of top-level but you can have array of objects and it is valid

    You can see more JSON Data Set examples if you want in this link

    • If you want to know more about JSON arrays you can read in w3schools JSON tutorial
    0 讨论(0)
提交回复
热议问题