To read JSON data in Python, use the built-in json module with json.load() for files and json.loads() for strings. json.load() reads directly from a file object and returns a Python dictionary or list, while json.loads() parses a JSON string into a Python object.
For reading a JSON file, the recommended approach uses a context manager to ensure the file is properly closed:
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data)This converts the JSON content into a standard Python dictionary, allowing you to access values using keys (e.g., data['key']). If the JSON data is provided as a string, such as from an API response, use json.loads():
import json
json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)
print(data['name']) # Output: AliceWhen working with large datasets or streaming data, consider using the ijson library for incremental parsing or the JSON Lines (JSONL) format where each line is a separate JSON object. Always handle potential errors like FileNotFoundError or json.JSONDecodeError using try-except blocks to ensure robust code.
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 OverflowThe 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.