71. Handling JSON Data

1. Parsing JSON from a String

Parsing a JSON string into a Python dictionary.

Copy

import json

json_string = '{"name": "Alice", "age": 30}'
parsed_data = json.loads(json_string)

print(parsed_data)  # Output: {'name': 'Alice', 'age': 30}

2. Converting Python Dictionary to JSON String

Converting a Python dictionary into a JSON-formatted string.

Copy

import json

data = {"name": "Bob", "age": 25}
json_string = json.dumps(data)

print(json_string)  # Output: {"name": "Bob", "age": 25}

3. Reading JSON from a File

Reading JSON data from a file and converting it into a Python dictionary.

Copy


4. Writing JSON to a File

Writing a Python dictionary to a JSON file.

Copy


5. Pretty-Printing JSON Data

Formatting JSON data for readability with indentation.

Copy


6. Converting Python Lists to JSON

Converting a Python list to a JSON-formatted string.

Copy


7. Handling Non-ASCII Characters in JSON

Ensuring non-ASCII characters are properly handled when converting to JSON.

Copy


8. Customizing JSON Serialization

Customizing the way objects are serialized by using a custom default function.

Copy


9. Handling JSON with Nested Structures

Parsing and working with JSON data that contains nested structures.

Copy


10. Deserializing JSON with Custom Classes

Converting JSON data into custom Python objects by subclassing json.JSONDecoder.

Copy


These snippets show how to handle JSON data in Python, including parsing, creating, reading, and writing JSON. The examples also cover customization options for handling non-ASCII characters, nested structures, and more complex serialization and deserialization scenarios.

Last updated