You are currently viewing Python json.loads() Method with Examples

The json loads() is a method from the json Python module that is used to parse 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.

Advertisements

Note that the json.loads() method can raise a ValueError if the input string is not valid JSON. In this article, we will discuss the json loads() method, its syntax, input param, and return type in detail with examples.

Related Articles :

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 file 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 it is similar to a Python dictionary. But 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. 

The Python json.loads() method is used to deserialize JSON data having str/bytes/byte-array into a Python object like a dictionary or list object.

  1. Pass json object as input to json.loads(), to convert it to a Dictionary
  2. Pass json array to json.loads(), to convert it to a List
  3. Pass json string to json.loads(), it is converted to a String
  4. Pass json object having integers to json.loads(), it is converted to a Integer
  5. Pass json object having real numbers to json.loads(), it is converted to a Float
  6. Pass json object having boolean values – true/false to json.loads(), it is converted to True/False.

1. Quick examples of json.loads()

Following are quick examples of how to use json.loads() method with different parameters.


import json

employee_json = """{"emp_id": 12,"emp_name": "Sravan","emp_sal": 46000.896,"technologies": ["Python","Java" ]}"""

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

# json.loads() with object_pairs_hook parameter
employee_Ordered_dict = json.loads(employee_json,object_pairs_hook=OrderedDict)
print(employee_Ordered_dict)
print(type(employee_Ordered_dict))

# json.loads() with object_hook parameter
employee_string = json.loads(employee_json,object_hook=str)
print(employee_string)
print(type(employee_string))

def finalsalary(emp_sal):
    return round(float(emp_sal), 2)
# json.loads() with parse_float parameter
employee_dictionary = json.loads(employee_json,parse_float=finalsalary)
print(employee_dictionary)

2. json loads() Module Explained

The json.loads() is a method from the json module that is used to parse 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.

2.1 Syntax of json.loads()

Following is the syntax of the json.loads() method. Notice that it takes 6 parameters. Note that the json.loads() method can raise a ValueError if the input string is not valid JSON.


# Syntax of json.loads()
json.loads(json_data, object_hook=None, parse_float=None, 
             parse_int=None, parse_constant=None, 
             object_pairs_hook=None, **kw)

2.2 Parameters – json.loads()

It takes 6 different parameters.

  • json_data – It is the json object
  • object_hook – Optional parameter which will be called with the result of every json data decoded. By using this parameter, we can convert json to any python object like a dictionary, string, list, tuple etc.
  • parse_float – is an optional parameter that will be called with the string of every json float to be decoded. It is similar to float(). We need to create a custom function and assign the custom function to it.
  • parse_int – is an optional parameter that will be called with the string of every json integer to be decoded. It is similar to int(). We need to assign the custom function to it.
  • parse_constant – is an optional parameter that will be called with ‘Infinity’,’NaN’ or ‘-Infinity’.
  • object_pairs_hook – is also an optional parameter that will be called with the result of every json data decoded with an ordered list of pairs.

3. json.loads() Python Example

Let’s have json data 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'>

4. Json to String Example

Let’s have previous json data and convert it into python string by passing ‘str’ to the object_hook parameter. In this case the json data is decoded into a string.


# Import modules
import json
from collections import OrderedDict

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

# json.loads() with object_hook parameter
employee_string = json.loads(employee_json,object_hook=str)
print(employee_string)
print(type(employee_string))

This example yields the below output. Notice that the json is converted to string type.


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

5. Using OrderedDict

Again, let’s have previous json data and convert it into python ordered dict by passing ‘OrderedDict‘ to the object_pairs_hook parameter of loads() method. In this case, the json data is decoded into ordered key-value pairs.

It is important to import OrderedDict from the collections module.


# Import modules
import json
from collections import OrderedDict

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

# json.loads() with object_pairs_hook parameter
employee_Ordered_dict = json.loads(employee_json,object_pairs_hook=OrderedDict)
print(employee_Ordered_dict)
print(type(employee_Ordered_dict))

Yields below output.


# Output:
# OrderedDict([('emp_id', 12), ('emp_name', 'Sravan'), ('emp_sal', 46000), ('technologies', ['Python', 'Java'])])
# <class 'collections.OrderedDict'>

We can see that our json data is decoded into ordered key-value pairs.

6. Using parse_float

Using loads(), now convert json into python dictionary with parse_float parameter. Here, we will round off “emp_sal” to 2 places.

Here, we need to create a custom function named – finalsalary with return – round(float(emp_sal), 2) and assign this to parse_float parameter.


# Import json module
import json

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

def finalsalary(emp_sal):
    return round(float(emp_sal), 2)

# json.loads() with parse_float parameter
employee_dictionary = json.loads(employee_json,parse_float=finalsalary)
print(employee_dictionary)

Yields below output.


# Output:
# {'emp_id': 12, 'emp_name': 'Sravan', 'emp_sal': 46000.79, 'technologies': ['Python', 'Java']}

The actual employee salary is 46000.7898. after decoding it is 46000.79.

7. Conclusion

In this article, you have learned json.loads() method is from the json module that is used to convert the json string to python objects like dictionary & list. In other words, it deserializes JSON data having str/bytes/byte-array into a Python object like a dictionary or list object.