Sometimes, we want to read JSON from a file with Python.
In this article, we’ll look at how to read JSON from a file with Python.
How to read JSON from a file with Python?
To read JSON from a file with Python, we can use the json.loads
method.
For instance, we write:
strings.json
{
"strings": [
{
"name": "city",
"text": "City"
},
{
"name": "phone",
"text": "Phone"
},
{
"name": "address",
"text": "Address"
}
]
}
main.py
import json
with open('strings.json') as f:
d = json.load(f)
print(d)
We call open
with the file path to the JSON file.
Then we call json.load
with the opened file.
And then we print d
which has the JSON string read from the file.
Therefore, d
is:
{'strings': [{'name': 'city', 'text': 'City'}, {'name': 'phone', 'text': 'Phone'}, {'name': 'address', 'text': 'Address'}]}
Since we used the with
statement, the file will automatically close once we’re done using it.
Conclusion
To read JSON from a file with Python, we can use the json.loads
method.