How to read a JSON file using python ?

Published: March 17, 2019

DMCA.com Protection Status

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