Python JSON

Python JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. Python provides a built-in library called json to handle JSON data, which can be used to convert Python objects into JSON format and vice versa.

Common Operations with JSON in Python

  • Converting Python objects to JSON
  • Converting JSON to Python objects

To use the json module, you need to import it first:

import json

Converting Python Objects to JSON

You can convert Python objects like dictionaries, lists, strings, numbers, and booleans into JSON format using the json.dumps() method.

Example: Python Object to JSON

import json

# Python dictionary
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Convert Python dictionary to JSON
person_json = json.dumps(person)
print(person_json)

Output:

{"name": "Alice", "age": 30, "city": "New York"}

Parameters of json.dumps()

  • indent: To pretty-print JSON (add indentation).
    json_string = json.dumps(person, indent=4)
    print(json_string)
    
  • sort_keys: To sort the keys of the JSON object.
    json_string = json.dumps(person, indent=4, sort_keys=True)
    print(json_string)
    
  • separators: Customize the separators between keys and values.
    json_string = json.dumps(person, separators=(",", ": "))
    print(json_string)
    

Writing JSON to a File

You can also write JSON data directly to a file using json.dump().

import json

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Writing JSON to a file
with open("person.json", "w") as json_file:
    json.dump(person, json_file, indent=4)

Converting JSON to Python Objects

To convert JSON data back into Python objects, you use the json.loads() method (for JSON strings) or json.load() (for JSON from files).

Example: JSON String to Python Object

import json

# JSON string
json_string = '{"name": "Alice", "age": 30, "city": "New York"}'

# Convert JSON string to Python dictionary
person = json.loads(json_string)
print(person)

Output:

{'name': 'Alice', 'age': 30, 'city': 'New York'}

Reading JSON from a File

You can read JSON data from a file and convert it back into a Python object using json.load().

import json

# Reading JSON from a file
with open("person.json", "r") as json_file:
    person = json.load(json_file)

print(person)

Handling JSON with Non-Standard Data Types

Sometimes, Python objects contain data types that aren’t directly convertible to JSON (e.g., Python datetime objects). You can define a custom encoder by subclassing json.JSONEncoder, or use the default parameter in json.dumps() to specify how to handle these types.

Example: Handling Non-Serializable Objects (like datetime)

import json
from datetime import datetime

# Custom function to convert datetime to string
def custom_serializer(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()  # Convert to ISO format string
    raise TypeError(f"Type {type(obj)} not serializable")

# Example with datetime object
now = datetime.now()

# Convert datetime object to JSON
json_string = json.dumps({"time": now}, default=custom_serializer)
print(json_string)

Example: Full Use Case – JSON with Lists and Nested Objects

import json

# Example data: a list of people
people = [
    {"name": "Alice", "age": 30, "city": "New York"},
    {"name": "Bob", "age": 25, "city": "Los Angeles"},
    {"name": "Charlie", "age": 35, "city": "Chicago"}
]

# Convert the list to JSON and pretty-print it
people_json = json.dumps(people, indent=4)
print(people_json)

# Save to a file
with open("people.json", "w") as json_file:
    json.dump(people, json_file, indent=4)

# Read the JSON back from the file
with open("people.json", "r") as json_file:
    loaded_people = json.load(json_file)

print(loaded_people)

Output:

The people.json file will contain:

[
    {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    },
    {
        "name": "Bob",
        "age": 25,
        "city": "Los Angeles"
    },
    {
        "name": "Charlie",
        "age": 35,
        "city": "Chicago"
    }
]

Error Handling in JSON Parsing

When working with JSON, it’s a good practice to handle potential errors. The json module raises json.JSONDecodeError if the JSON data is malformed.

Example: Handling JSON Decoding Errors

import json

invalid_json_string = '{"name": "Alice", "age": 30, "city": "New York"'

try:
    person = json.loads(invalid_json_string)
except json.JSONDecodeError as e:
    print(f"JSON decode error: {e}")

Summary of Key Functions in the json Module

  • json.dumps(): Converts a Python object to a JSON string.
  • json.dump(): Writes a Python object to a file as JSON.
  • json.loads(): Converts a JSON string to a Python object.
  • json.load(): Reads JSON from a file and converts it to a Python object.

Conclusion

The json module in Python is essential for working with JSON data. It allows you to easily convert between Python objects and JSON, and it is very useful for handling data exchange in web applications or reading and writing configuration files.

Leave a Reply 0

Your email address will not be published. Required fields are marked *