Python - Convert dictionary to JSON and parse JSON string

By xngo on June 27, 2019

Python provides a built-in package called json, which can be used to work with JSON data.

Convert dictionary to JSON

import json
 
# Example of Python dictionary.
employee = {
                "id"   :  93423,
                "name" : "John",
                "city" : "Montréal"
            }
 
# Convert to JSON.
json_result = json.dumps(employee)
 
# Print JSON.
print(json_result)

Output

{"name": "John", "city": "Montr\u00e9al", "id": 93423}

Parse JSON string back to Python

import json
 
# A JSON string.
json_str = '{"city": "Montr\u00e9al", "id": 93423, "name": "John"}'
 
# Convert JSON string to Python dictionary.
emp = json.loads(json_str)
 
# Access dictionary data.
print(emp["id"])
print(emp["city"])

Output

93423
Montréal

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.