Reading JSON from a file? Reading JSON from a file? python python

Reading JSON from a file?


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

import jsonwith 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?.


Here is a copy of code which works fine for me

import jsonwith open("test.json") as json_file:    json_data = json.load(json_file)    print(json_data)

with the data

{    "a": [1,3,"asdf",true],    "b": {        "Hello": "world"    }}

you may want to wrap your json.load line with a try catch because invalid JSON will cause a stacktrace error message.


The problem is using with statement:

with open('strings.json') as json_data:    d = json.load(json_data)    pprint(d)

The file is going to be implicitly closed already. There is no need to call json_data.close() again.


matomo