Reading JSON from a file?

前端 未结 7 1846
無奈伤痛
無奈伤痛 2020-11-22 03:33

I am getting a bit of headache just because a simple looking, easy statement is throwing some errors in my face.

I have a json file called strings.json like this:

7条回答
  •  别那么骄傲
    2020-11-22 04:00

    The json.load() method (without "s" in "load") can read a file directly:

    import json
    
    with open('strings.json') as f:
        d = json.load(f)
        print(d)
    

    You were using the json.loads() method, which is used for string arguments only.

    Edit: The new message is a totally different problem. In that case, there is some invalid json in that file. For that, I would recommend running the file through a json validator.

    There are also solutions for fixing json like for example How do I automatically fix an invalid JSON string?.

提交回复
热议问题