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.
The error you get with json.loads is a totally different problem. In that case, there is some invalid JSON content 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?.
Answer from ubomb on Stack Overflowpython - Reading JSON from a file - Stack Overflow
Pulling data from local json file
How do I write and load json files?
You can actually bypass the json.dumps and json.loads and just do this
import jsonMore on reddit.com
data = {'name':'chinpanze','age':24}
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
with open('data.json') as json_file:
read = json.load(json_file)
print(read)
JSON load() vs loads()
load() loads JSON from a file or file-like object
loads() loads JSON from a given string or unicode object
It's in the documentation
More on reddit.comVideos
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.
The error you get with json.loads is a totally different problem. In that case, there is some invalid JSON content 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 json
with 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.