Working with JSON in Python

What is JSON?

JSON (JavaScript Object Notation) is a simple format for storing and exchanging data. It is easy to read and write for both humans and machines. Python has a built-in module that allows us to work with JSON data easily called json.

Using JSON in Python

Importing the JSON Module

To start using JSON in Python, you first need to import the json module:

import json # Import the JSON module

Parsing JSON

You can convert a JSON string into a Python dictionary using the json.loads() function.

Example:

import json # Import the JSON module

# A JSON string representing a popular Filipino Bread
json_string = '{"name": "Pandesal", "type": "bread roll", "ingredients": ["flour", "yeast", "sugar", "salt", "water"]}'

# Convert JSON string to a Python dictionary
bread_data = json.loads(json_string)

# Access the data
print(bread_data["name"])  # Output: Pandesal

Converting Python to JSON

To convert a Python object (like a dictionary) into a JSON string, use the json.dumps()function.

Example:

import json # Import the JSON module

# A Python dictionary representing a famous Filipino dessert bread
dessert_bread_data = {
    "name": "Ensaymada",
    "type": "sweet bread",
    "toppings": ["butter", "cheese", "sugar"],
    "is_popular": True
}

# Convert the Python dictionary to a JSON string
json_string = json.dumps(dessert_bread_data)

# Print the JSON string
print(json_string)  
# Output: {"name": "Ensaymada", "type": "sweet bread", "toppings": ["butter", "cheese", "sugar"], "is_popular": true}

Supported Data Types

Dictionary (dict)JSON Object
ListJSON Array
TupleJSON Array
StringJSON String
IntegerJSON Number
FloatJSON Number
Boolean (True/False)JSON true/false
NoneJSON null
You can convert various Python objects to JSON, including dictionaries, lists, and more.

Example:

import json # Import the JSON module

# A dictionary with details about various types of Filipino delicacies
delicacy_details = {
    "pandesal": {
        "flavor": "savory",
        "texture": "soft",
        "country_of_origin": "Philippines"
    },
    "puto": {
        "flavor": "sweet",
        "texture": "fluffy",
        "country_of_origin": "Philippines"
    },
    "bibingka": {
        "flavor": "sweet and savory",
        "texture": "moist",
        "country_of_origin": "Philippines"
    }
}

# Convert the dictionary to JSON
json_data = json.dumps(bread_details)

# Print the JSON string
print(json_data)  
# Output: {"bibingka": {"flavor": "sweet and savory", "texture": "moist", "country_of_origin": "Philippines"}, "pandesal": {"flavor": "savory", "texture": "soft", "country_of_origin": "Philippines"}, "puto": {"flavor": "sweet", "texture": "fluffy", "country_of_origin": "Philippines"}}

Formatting JSON Output

To format the JSON output for better readability, use indentation.

Example:

import json # Import the JSON module

# Dictionary representing a delicacy in the Philippines
delicacy_data = {
    "name": "Suman",
    "type": "rice cake",
    "ingredients": ["glutinous rice", "coconut milk", "sugar"],
    "served_with": ["mango", "latik"]
}

# Convert and format the dictionary to a JSON string
formatted_json = json.dumps(delicacy_data, indent=4)

# Print the formatted JSON string
print(formatted_json)

# Output:
# {
#     "ingredients": [
#         "glutinous rice",
#         "coconut milk",
#         "sugar"
#     ],
#     "name": "Suman",
#     "served_with": [
#         "mango",
#         "latik"
#     ],
#     "type": "rice cake"
# }

Sorting JSON Keys

You can sort the keys in your JSON output using the sort_keys parameter.

Example:

import json # Import JSON module

# A dictionary representing a type of Filipino bread
tasty_breads = {
    "name": "Pan de Coco",
    "type": "sweet bread",
    "filling": "coconut",
    "texture": "soft",
    "is_traditional": True
}

# Convert and sort the dictionary to a JSON string
sorted_json = json.dumps(tasty_breads, indent=4, sort_keys=True)

# Print the sorted JSON keys
print(sorted_json)

# Output:
# {
#     "filling": "coconut",
#     "is_traditional": true,
#     "name": "Pan de Coco",
#     "texture": "soft",
#     "type": "sweet bread"
# }

Scroll to Top