Example of how to read a JSON file using python:
Read a JSON file with python
Let's consider a JSON (JavaScript Object Notation) file called data.json:
{
"abstract": "Hello how are you today ?",
"link_01": {
"name": "Welcome page",
"priority": "1"
},
"link_02": {
"name": "Home page",
"priority": "2"
}
}
To read the file with python:
with open('data.json') as json_data:
print(type(json_data))
returns
<class '_io.TextIOWrapper'>
Save the JSON data in a dictionary
To stock the JSON data in a python dictionary, a solution is to use load() from the json module, example:
import json
with open('data.json') as json_data:
data_dict = json.load(json_data)
print(data_dict)
returns
{'abstract': 'Hello how are you today ?', 'link_02': {'priority': '2', 'name': 'Home page'}, 'link_01': {'priority': '1', 'name': 'Welcome page'}}
Save the JSON data in a string
Transfer the data in a string from the dictionary called here "data_dict" using dumps:
import json
with open('data.json') as json_data:
data_dict = json.load(json_data)
data_str = json.dumps(data_dict)
print(data_str)
returns
{"abstract": "Hello how are you today ?", "link_02": {"name": "Home page", "priority": "2"}, "link_01": {"name": "Welcome page", "priority": "1"}}
Note: to reverse the previous transformation: string to dictionary using the function loads():
import json
with open('data.json') as json_data:
data_dict = json.load(json_data)
data_str = json.dumps(data_dict)
data_dict_02 = json.loads(data_str)
print(data_dict_02)
References
Links | Site |
---|---|
Importing JSON file with python | stackoverflow |
Reading and Writing JSON to a File in Python | stackabuse.com |
JSON - Introduction | w3schools |
Parsing JSON | docs.python-guide.org |
Parsing values from a JSON file? | stackoverflow |
Reading JSON from a file? | stackoverflow |
JSON encoding and decoding with Python | pythonspot |
parse JSON values by multilevel keys | stackoverflow |
Working with JSON and Django | godjango |
How can I edit/rename keys during json.load in python? | stackoverflow |
Items in JSON object are out of order using “json.dumps”? | stackoverflow |
json.dumps messes up order | stackoverflow |
JSON Example | json.org |
circlecell/jsonlint.com | jsonlint.com |
jsonlint | jsonlint |
zaach/jsonlint | jsonlint github |