Python – Parse JSON String

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 – json.loads()

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

#import statement
import json
#parse json string
pythonObj = json.loads(jsonStr)
Run this program

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}
Run this program

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}]
Run this program

Example 1: Parse JSON String to Python Dictionary

In this example, let us initialize a string with a valid JSON data. We will use json.loads() function to parse this JSON String.

Python Program

import json

# json string
jsonStr =  '{"name":"Tesla", "age":2, "city":"New York"}'

# parse json file
pythonObj = json.loads(jsonStr)
#print type of object
print(type(pythonObj))
#access elements in the object
name = pythonObj['name']
print(name)
Run this program

Output

<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.

Example 2: Parse JSON String to Python List

In this example, let us initialize a JSON string with an array of elements and we will use json.loads() function to parse this JSON String into a Python List.

Python Program

import json

# json string
jsonStr =  '[{"name":"Tesla", "age":2, "city":"New York"}, { "name":"Tesla", "age":2, "city":"Boston"}]'

# parse json file
pythonObj = json.loads(jsonStr)
print(type(pythonObj))
print(type(pythonObj[0]))

city = pythonObj[1]['city']
print(city)
Run this program

Output

<class '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.

Example 3: json.decoder.JSONDecodeError

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

jsonStr =  '"name":"Tesla", "age":2'
pythonObj = json.loads(jsonStr)
name = pythonObj['name']
print(name)
Run this program

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 tutorial of Python Examples, we learned how to parse a JSON string in Python, with the help of well detailed example programs.