You are currently viewing Python Read JSON File

The json.load() method is used to read a JSON file in Python whereas json.loads() is used to parse a JSON string into a Python object. These two methods are from the json module that is used to work with JSON in Python.

Advertisements

Related:

Python JSON Introduction

JSON stands for Javascript object notation which is mostly used to serialize structured data and exchange it over web applications. Python has a built-in package called json to work with JSON files or strings. The data in the JSON is made up of the form of key/value pairs and they can be enclosed with {}.

Look wise JSON is similar to a Python dictionary where JSON keys must be string-type objects with a double-quoted and values can be any datatype such as string, integer, nested JSON, a list, a tuple, or even another dictionary. 

In order to work with JSON string or a file, Python provides a json module. This module contains several methods to read, write, or parse JSON.

Using json.load(), we can load a file in different ways.

  1. Load json from a file into a dictionary
  2. Specifying object_hook parameter within json.load() function.
  3. Specifying object_pairs_hook parameter within json.load() function.
  4. Specifying parse_int,parse_float parameters within json.load() function.

2. json.load() to Read JSON File in Python

The json.load() method is used to read a JSON file or parse a JSON string and convert it into a Python object. In python, to decode the json data from a file first, we need to load the JSON file into the python environment by using the open() function and use this file object to load() method.

2.1 Syntax of json.load()

The syntax for json.load() method is as follows:


# Syntax of json.load() method
json.load(file, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

2.2 Parameters of json.load()

json.load() takeseveral optional arguments.

  • file: Input file path to read.
  • cls: A custom decoder class that is used to convert the JSON data into a Python object. This argument is useful when you want to customize the decoding process.
  • object_hook: A function that is called for every object literal in the JSON data, and can be used to transform the object into another object. This argument is useful when you want to customize the decoding process.
  • parse_float: A function that is called for every float value in the JSON data, and can be used to transform the float into another value.
  • parse_int: A function that is called for every int value in the JSON data, and can be used to transform the int into another value.
  • parse_constant: A function that is called for every JSON constant (e.g. null, true, false) in the JSON data, and can be used to transform the constant into another value.
  • object_pairs_hook: A function that is called for every object literal with its key-value pairs, and can be used to transform the object into another object.

3. Python Read JSON File Example

Let’s have a file named details.json which stores country details and read this JSON file into a Python object using the loads() method.

Following are the steps to read JSON files in Python

  • Step 1 – Import json module.
  • Step 2 – Open the file using the open() method.
  • Step 3 – Read the file using the file object created in step 2.

3.1 Read Json with default options

By using the above steps, let’s read the details.json file using load() method with no optional parameters. This just uses the file object to read.


# Import JSON module
import json

# Read json file
with open("details.json", "r") as read_file:
    # json.load()
    details = json.load(read_file)
    print(details)

# Output:
# {'Country': 'USA', 'Code': 'EAO908', 'States': ['Florida', 'Alaska', 'Texas'], 'Software': 30.56, 'Businessmen': 60, 'Lakes_Available': True}

This reads the contents of the file details.json and parses it using json.load() and returns a Python object details.

Let’s display values based on keys from a dictionary that is converted from JSON data.


# Import json module
import json

# Read json file
with open("details.json", "r") as read_file:
    # json.load()
    details = json.load(read_file)

    # print json elements
    print(details['Country'])
    print(details['Code'])
    print(details['States'])
    print(details['Lakes_Available'])

This example yields the below output.


# Output:
USA
EAO908
['Florida', 'Alaska', 'Texas']
True

We are displaying values based on four keys one by one.

3.2 Using object_hook to Read to JSON string

Let’s read the json data from a file to a string by assigning ‘str‘ to the object_hook parameter.


import json

with open("details.json", "r") as read_p:
  # json.load() with object_hook parameter
    details = json.load(read_p,object_hook=str)
    print(details)

# Output:
# {'Country': 'USA', 'Code': 'EAO908', 'States': ['Florida', 'Alaska', 'Texas'], 'Software': 30.56, 'Businessmen': 60, 'Lakes_Available': True}

The data present in json file (details.json) is decoded into the string.

3.3 Using object_pairs_hook to Load to Tuple

Let’s load the json data from a file to a tuple by assigning ‘tuple‘ to the object_pairs_hook parameter.


import json

with open("details.json", "r") as read_p:
  # json.load() with object_pairs_hook parameter
    tuple1 = json.load(read_p,object_pairs_hook=tuple)
    print(tuple1)

# Output:
# (('Country', 'USA'), ('Code', 'EAO908'), ('States', ['Florida', 'Alaska', 'Texas']), ('Software', 30.56), ('Businessmen', 60), ('Lakes_Available', True))

The data present in json file (details.json) is dedcoded into the tuple.

3.4 Using object_pairs_hook

Let’s decode the json data from a file to list by passing ‘list’ to the object_pairs_hook parameter.


import json

with open("details.json", "r") as read_p:
  # json.load() with object_pairs_hook parameter
    list1 = json.load(read_p,object_pairs_hook=list)
    print(list1)

# Output:
# [('Country', 'USA'), ('Code', 'EAO908'), ('States', ['Florida', 'Alaska', 'Texas']), ('Software', 30.56), ('Businessmen', 60), ('Lakes_Available', True)]

The data present in json is converted into the list.

3.5 Using parse_float

Let’s load the json data from a file along with float (‘Software’) to a dictionary.


import json
import math

def percent_software(Software):
    return math.ceil(float(Software))

with open("details.json", "r") as read_p:
  # json.load() with parse_float parameter
    final = json.load(read_p,parse_float=percent_software)
    print(final)

# Output:
# {'Country': 'USA', 'Code': 'EAO908', 'States': ['Florida', 'Alaska', 'Texas'], 'Software': 31, 'Businessmen': 60, 'Lakes_Available': True}

We created a custom function that will return the highest integer value (Using ceil() function). Previously the ‘Software is 30.6, After decoding, it is 31.

4. Read JSON from a String in Python

The json loads() is a method from the json Python module that is used to parse/read a JSON (JavaScript Object Notation) string and convert it into a Python object. The method takes a JSON string as an input param and returns a Python object, usually a dictionary or a list, depending on the structure of the JSON string.

Let’s have json string that include employee details and convert it into a python dictionary by passing json object to json.loads() method. Here we use “”” to create a long multi-line string.


# Import json module
import json

# json string
employee_json = """{"emp_id": 12,"emp_name": "Sravan",
                    "emp_sal": 46000,
                    "technologies": ["Python","Java" ]}"""

# json.loads() 
employee_dictionary = json.loads(employee_json)
print(employee_dictionary)
print(type(employee_dictionary))

This example yields the below output. Notice that our json is converted into dictionary (Class – dict).


# Output:
{'emp_id': 12, 'emp_name': 'Sravan', 'emp_sal': 46000, 'technologies': ['Python', 'Java']}
<class 'dict'>

5. Conclusion

In this article, you have learned how to read the JSON from a file using json.load() function. As part of this article. we explained json.load() method by considering all the parameters with examples. To loas the json file into python environment, we used open() method.