Working with JSON in Python: An Introduction

Explore JSON (JavaScript Object Notation), a text-based syntax for storing and exchanging data. Learn how to use Python’s built-in json package to handle JSON data efficiently, making data manipulation and integration straightforward in your applications.



Python JSON

JSON (JavaScript Object Notation) is a syntax used for storing and exchanging data, written as text.

JSON in Python

Python comes with a built-in package called json, which allows you to work with JSON data.

Importing the JSON Module

First, you need to import the json module:

Syntax
import json

Parsing JSON - Convert from JSON to Python

If you have a JSON string, you can parse it using the json.loads() method. The result will be a Python dictionary.

Example

import json

# JSON string
json_string = '{ "name":"Alice", "age":25, "city":"Paris"}'

# parse json_string
parsed_data = json.loads(json_string)

# the result is a Python dictionary
print(parsed_data["age"])
        
Output
25

Converting from Python to JSON

If you have a Python object, you can convert it into a JSON string using the json.dumps() method.

Example

import json

# Python dictionary
python_dict = {
  "name": "Alice",
  "age": 25,
  "city": "Paris"
}

# convert into JSON string
json_string = json.dumps(python_dict)

# the result is a JSON string
print(json_string)
        
Output
{"name": "Alice", "age": 25, "city": "Paris"}

Supported Python Data Types

Python objects of the following types can be converted into JSON strings:

  • dict
  • list
  • tuple
  • string
  • int
  • float
  • True
  • False
  • None
Example

import json

print(json.dumps({"name": "Alice", "age": 25}))
print(json.dumps(["apple", "orange"]))
print(json.dumps(("apple", "orange")))
print(json.dumps("hello world"))
print(json.dumps(100))
print(json.dumps(99.99))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
        
Output

{"name": "Alice", "age": 25}
["apple", "orange"]
["apple", "orange"]
"hello world"
100
99.99
true
false
null
        

Python to JSON Conversion

When converting Python objects to JSON, they are transformed into their equivalent JSON types:

Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null
Example

import json

data = {
  "name": "Alice",
  "age": 25,
  "married": True,
  "divorced": False,
  "children": ("Ann", "Billy"),
  "pets": None,
  "cars": [
    {"model": "Tesla Model 3", "mpg": 130.9},
    {"model": "Ford Mustang", "mpg": 24.1}
  ]
}

print(json.dumps(data))
        
Output
{"name": "Alice", "age": 25, "married": true, "divorced": false, "children": ["Ann", "Billy"], "pets": null, "cars": [{"model": "Tesla Model 3", "mpg": 130.9}, {"model": "Ford Mustang", "mpg": 24.1}]}

Formatting the JSON Result

The json.dumps() method has parameters to make the output more readable, such as indentation and separators.

Example

import json

# formatted JSON string with indentation
formatted_json = json.dumps(data, indent=4)
print(formatted_json)
        
Output

{
    "name": "Alice",
    "age": 25,
    "married": true,
    "divorced": false,
    "children": [
        "Ann",
        "Billy"
    ],
    "pets": null,
    "cars": [
        {
            "model": "Tesla Model 3",
            "mpg": 130.9
        },
        {
            "model": "Ford Mustang",
            "mpg": 24.1
        }
    ]
}
        

Customizing Separators

You can change the default separators using the separators parameter:

Example

import json

# custom separators
custom_separators_json = json.dumps(data, indent=4, separators=(". ", " = "))
print(custom_separators_json)
        
Output

{
    "name" = "Alice". 
    "age" = 25. 
    "married" = true. 
    "divorced" = false. 
    "children" = [
        "Ann". 
        "Billy"
    ]. 
    "pets" = null. 
    "cars" = [
        {
            "model" = "Tesla Model 3". 
            "mpg" = 130.9
        }. 
        {
            "model" = "Ford Mustang". 
            "mpg" = 24.1
        }
    ]
}
        

Sorting the JSON Keys

The json.dumps() method allows you to sort the keys in the output using the sort_keys parameter:

Example

import json

# sorted JSON keys
sorted_keys_json = json.dumps(data, indent=4, sort_keys=True)
print(sorted_keys_json)
        
Output

{
    "age": 25,
    "cars": [
        {
            "model": "Tesla Model 3",
            "mpg": 130.9
        },
        {
            "model": "Ford Mustang",
            "mpg": 24.1
        }
    ],
    "children": [
        "Ann",
        "Billy"
    ],
    "divorced": false,
    "married": true,
    "name": "Alice",
    "pets": null
}