Python Read JSON File


Python Read JSON File

Python Read JSON File

To read JSON file in Python, open file in read mode, and parse it using json.loads() function.

In this tutorial, we will learn how to read a JSON file to a string, and access elements of the JSON content.

Examples

1. Read JSON file

In this example, we read data.json file with JSON content. We will load this content into a Python object, so that we can access the elements and key:value pairs.

Following is the data.json file that we are reading in the Python program. The content is a single object with three name:value pairs.

data.json

{
    "a": 21,
    "b": 42,
    "c": 73
}

Python Program

import json

fileObject = open("data.json", "r")
jsonContent = fileObject.read()
aList = json.loads(jsonContent)
print(aList)
print(aList['a'])
print(aList['b'])
print(aList['c'])

Output

{'a': 21, 'b': 42, 'c': 73}
21
42
73

2. Read JSON file that contains array of objects

In this example, we read data.json file with JSON content. The JSON data is an array of objects.

data.json

[
    {
        "a": 85,
        "b": 71,
        "c": 39
    },
    {
        "d": 18,
        "e": 72,
        "f": 23
    },
    {
        "g": 18,
        "h": 62,
        "i": 43
    }
]

Python Program

import json

fileObject = open("data.json", "r")
jsonContent = fileObject.read()
aList = json.loads(jsonContent)
print(aList[0])
print(aList[0]['c'])

Output

{'a': 85, 'b': 71, 'c': 39}
39

Summary

In this Python JSON Tutorial, we learned how to read JSON file in Python and access values from the JSON content.