How to Parse JSON String in Python?


Python - Parse JSON String

To parse JSON String into a Python object, you can use json inbuilt python library. json package has loads() function to parse a JSON string.

In this tutorial, we will learn how to parse JSON string using json package, with the help of well detailed exampple Python programs.

Syntax of json.loads()

Following code snippet depicts the syntax to import json package and parse json String using json.loads().

import json

# Parse json string
python_obj = json.loads(json_str)

where jsonStr is a string that contains JSON data and json.loads() returns Python object. Based on the structure of JSON String, the type of the returned object would be list or dictionary.

Based on the JSON string, json.loads() return either Python Dictionary or Python List.

If JSON string is of the following format, then json.loads() returns a Python Dictionary.

{key:value, key:value, key:value}

If JSON string is of the following format, then json.loads() returns a Python List.

[item, item, item]

If JSON string is of the following format, then json.loads() returns a Python List of Dictionaries.

[{key:value, key:value}, {key:value}, {key:value}]

Examples

In the following example, we shall take a JSON string with data of a specific JSON data type, and parse them into a Python object using json.loads() function. We shall cover examples with JSON datatypes like dictionary, array, etc., and cover a scenario in the last that shows what happens when the JSON string data is not valid.

1. Parse JSON string to Python dictionary

In this example, we are given a valid JSON data as a string. We have to parse this JSON string using json.loads() function.

Steps

  1. Import json library.
  2. Given a JSON string in variable json_str.
  3. Call json.loads() function and pass the given JSON string json_str as argument.
json.loads(json_str)
  1. The json.loads() function returns a Python object by parsing the data in given argument. Based on the type of data in JSON string, the type of the Python object is decided. In this example, we are given a JSON dictionary data in the JSON string, therefore, this data translates to Python dictionary.
python_obj = json.loads(json_str)
  1. You may print the type of returned Python object using type() built-in function.
print(type(python_obj))
  1. You can also access the items in the Python dictionary using respective keys.

Program

The complete program to parse the given JSON string into a Python object using json.loads() method.

Python Program

import json

# Given JSON string
json_str =  '{"name":"Tesla", "age":2, "city":"New York"}'

# parse json string
python_obj = json.loads(json_str)

# print type of object
print("Type of object :", type(python_obj))

# Read value from Python dictionary using key
name = python_obj['name']
print(name)

Output

Type of object : <class 'dict'>
Tesla

The JSON String in this example is a single element with multiple key:value pairs inside. Hence, the datatype of the parsed JSON string by loads() function is dictionary. Using this dictionary object, you can access value for a given key using indexing mechanism. Also, you can perform all Dictionary Operations on this Python Dictionary object.

2. Parse JSON string to Python list

In this example, we are given a JSON string, where the data in the JSON string is an array of elements. We shall use json.loads() function to parse this JSON String. The Python equivalent of a JSON Array is a Python List.

Python Program

import json

# Given JSON string
json_str =  '[{"name":"Tesla", "age":2, "city":"New York"}, { "name":"Tesla", "age":2, "city":"Boston"}]'

# parse json string
python_obj = json.loads(json_str)

# print types
print("Type of python object :", type(python_obj))
print("Type of item in list  :", type(python_obj[0]))

# Access inner elements
city = python_obj[1]['city']
print(city)

Output

Type of python object : <class 'list'>
Type of item in list  : <class 'dict'>
Boston

The JSON String in this example is an array of elements. Therefore, the datatype of the parsed JSON string by loads() function is a Python List. And the datatype of elements in the list is dictionary.

3. json.decoder.JSONDecodeError when JSON string is not valid

Sometimes, you may encounter json.decoder.JSONDecodeError. This error is thrown by json.loads() function when you try to load an invalid JSON string.

Python Program

import json

# Given JSON string
json_str =  '"name":"Tesla", "age":2'

# parse JSON string
python_obj = json.loads(json_str)

name = python_obj['name']
print(name)

The format of the given JSON string is not correct. Therefore, json.loads() function could not decode and raised JSONDecodeError exception.

Output

Traceback (most recent call last):
  File "d:/workspace/python/example.py", line 4, in <module>
    pythonObj = json.loads(jsonStr)
  File "C:\Users\PE\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "C:\Users\PE\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 7 (char 6)

Summary

In this Python JSON Tutorial, we learned how to parse a JSON string in Python, with the help of well detailed example programs.