How to use JSON in Python

How to use JSON in Python

In this comprehensive tutorial, we delve into the world of working with JSON data in Python. From serializing and deserializing JSON to reading from and writing to JSON files, this video provides a step-by-step guide to mastering these essential skills.

🌟 What You’ll Learn:

  • Serializing JSON in Python: Convert Python objects into JSON strings with ease.
  • Deserializing JSON in Python: Transform JSON strings back into Python objects.
  • Reading JSON Files: Efficiently load and process data from JSON files.
  • Writing JSON Files: Save your data to JSON files seamlessly.

Tutorial Video

Python Code

Working with JSON data in Python is a valuable skill, especially when dealing with APIs, document databases, or data exchange.
Python has a built-in package called JSON, which can be used to work with JSON data.

Look, It’s JSON!

Consider the following JSON snippet:

{
    "firstName": "Jane",
    "lastName": "Doe",
    "hobbies": ["running", "sky diving", "singing"],
    "age": 35,
    "children": [
        {"firstName": "Alice", "age": 6},
        {"firstName": "Bob", "age": 8}
    ]
}

Serializing JSON

To convert a Python object (such as a dictionary) into a JSON string, use json.dumps()

import json

data = {
    "firstName": "Jane",
    "lastName": "Doe",
    "hobbies": ["running", "sky diving", "singing"],
    "age": 35
}

json_string = json.dumps(data, indent=4)  # Indent for readability
print(json_string)


Deserializing JSON

To load a JSON string into a Python object, use json.loads()

  • Deserialization converts JSON objects into Python objects.
  • load()/loads() can deserialize JSON from a string or file.
  • Typically used when JSON data is obtained from another program or in string format.
loaded_data = json.loads(json_string)
print(loaded_data["firstName"])  # Access individual fields
print(loaded_data["lastName"])  # Access individual fields
print(loaded_data["hobbies"])  # Access individual fields
print(loaded_data["age"])  # Access individual fields

Reading JSON File

Let’s say you have a JSON file named example.json:

# Read JSON data from file
with open("example.json") as file:
    loaded_data = json.load(file)
    
# Print total items
print(f"Total Items: {len(loaded_data)}")

# Print each key-value pair
for key, value in loaded_data.items():
    print(f"{key}: {value}")

Writing JSON File:

# New person's data
new_data = {
    "firstName": "John",
    "lastName": "Smith",
    "hobbies": ["reading", "painting", "cooking"],
    "age": 40,
    "children": [
        {"firstName": "Emma", "age": 10},
        {"firstName": "Jack", "age": 12}
    ]
}

# Write data to a JSON file
with open("sample.json", "w") as json_file:
    json.dump(new_data, json_file, indent=4)

print("JSON file 'example.json' created successfully!")