71. Handling JSON Data

Here are 10 Python code snippets demonstrating Handling JSON Data using Python's json module. These examples cover parsing JSON data and creating JSON data.


1. Parsing JSON from a String

Parsing a JSON string into a Python dictionary.

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.

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.


4. Writing JSON to a File

Writing a Python dictionary to a JSON file.


5. Pretty-Printing JSON Data

Formatting JSON data for readability with indentation.


6. Converting Python Lists to JSON

Converting a Python list to a JSON-formatted string.


7. Handling Non-ASCII Characters in JSON

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


8. Customizing JSON Serialization

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


9. Handling JSON with Nested Structures

Parsing and working with JSON data that contains nested structures.


10. Deserializing JSON with Custom Classes

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


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