Skip to main content

Introduction to Python JSON

Python JSON

The json module provides functions for working with JSON (JavaScript Object Notation) data.

JSON is a lightweight data interchange format that is widely used for transmitting and storing data.

The json module allows you to convert Python objects to JSON strings and vice versa. Here's an overview of how to work with JSON in Python using the json module.

Importing the json Module

Before using the functions from the json module, you need to import it.

import json

Converting Python Objects to JSON

The json module provides the json.dumps() function to convert a Python object to a JSON string. You can pass the Python object as an argument to json.dumps() to get the corresponding JSON representation.

As an example:

# Convert a Python dictionary to a JSON string
data = {
"name": "Alice",
"age": 25,
"city": "New York"
}
json_string = json.dumps(data)
print(json_string)
# Output: {"name": "Alice", "age": 25, "city": "New York"}

In this example:

  • The json.dumps() function also accepts additional parameters like indent and sort_keys to control the formatting and sorting of the resulting JSON string.

Converting JSON to Python Objects

The json module provides the json.loads() function to convert a JSON string to a Python object. You can pass the JSON string as an argument to json.loads() to obtain the corresponding Python object.

As an example:

# Convert a JSON string to a Python dictionary
json_string = '{"name": "Bob", "age": 30, "city": "London"}'
data = json.loads(json_string)
print(data)
# Output: {'name': 'Bob', 'age': 30, 'city': 'London'}

In this example:

  • The json.loads() function automatically converts the JSON string into the appropriate Python data types, such as dictionaries, lists, strings, numbers, and booleans.

Working with JSON Files

The json module also provides functions for working with JSON files. You can use json.dump() to write a Python object as JSON to a file, and json.load() to read a JSON file and convert it to a Python object.

As an example:

# Write Python data to a JSON file
data = {
"name": "Alice",
"age": 25,
"city": "New York"
}
with open("data.json", "w") as file:
json.dump(data, file)

# Read JSON data from a file
with open("data.json", "r") as file:
data = json.load(file)
print(data)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

In this example:

  • The `json.dump() function writes the Python object to the file "data.json" as JSON.
  • The json.load() function reads the JSON data from the file and converts it back to a Python object.