Skip to content

Python3 JSON Data Parsing

JSON (JavaScript Object Notation) is a lightweight data interchange format.

If you are not familiar with JSON, you can first read our JSON Tutorial.

In Python3, you can use the json module to encode and decode JSON data. It includes two functions:

  • json.dumps(): Encodes data.
  • json.loads(): Decodes data.

During the encoding and decoding process of JSON, Python’s primitive types and JSON types are converted to each other. The specific conversion mappings are as follows:

Python Encoded to JSON Type Conversion Table:

Section titled “Python Encoded to JSON Type Conversion Table:”
Python JSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True true
False false
None null

JSON Decoded to Python Type Conversion Table:

Section titled “JSON Decoded to Python Type Conversion Table:”
JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

The following example demonstrates converting Python data structures to JSON:

#!/usr/bin/python3

import json

# Python dictionary type converted to JSON object
data = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'https://www.runoob.com'
}

json_str = json.dumps(data)
print ("Python raw data:", repr(data))
print ("JSON object:", json_str)

Output of the above code:

Python raw data: {'no': 1, 'name': 'Runoob', 'url': 'https://www.runoob.com'}
JSON object: {"no": 1, "name": "Runoob", "url": "https://www.runoob.com"}

From the output results, you can see that simple types after encoding are very similar to their original repr() output.

Continuing from the above example, we can convert a JSON-encoded string back to a Python data structure:

#!/usr/bin/python3

import json

# Python dictionary type converted to JSON object
data1 = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}

json_str = json.dumps(data1)
print ("Python raw data:", repr(data1))
print ("JSON object:", json_str)

# Convert JSON object to Python dictionary
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])

Output of the above code:

Python raw data: {'name': 'Runoob', 'no': 1, 'url': 'http://www.runoob.com'}
JSON object: {"name": "Runoob", "no": 1, "url": "http://www.runoob.com"}
data2['name']:  Runoob
data2['url']:  http://www.runoob.com

If you are dealing with files instead of strings, you can use json.dump() and json.load() to encode and decode JSON data. For example:

# Write JSON data
with open('data.json', 'w') as f:
    json.dump(data, f)

# Read data
with open('data.json', 'r') as f:
    data = json.load(f)

For more information, please refer to: https://docs.python.org/3/library/json.html