Mastering Python's JSON Module ๐Ÿ“

JSON data icon

Mastering Python's JSON Module ๐Ÿ“

The json module in Python is essential for converting JSON data to Python objects and vice versa, handling formatting, and managing JSON files seamlessly.

1. JSON String ↔ Python Object

import json

data = '{"name": "John", "age": 30, "languages": ["Python", "JavaScript"]}'
obj = json.loads(data)
print(obj, type(obj))  # {'name': 'John', 'age': 30, 'languages': ['Python', 'JavaScript']}

s = json.dumps(obj)
print(s, type(s))  # String

2. Pretty Printing with Indentation

import json

obj = {"name": "Jane", "age": 25, "city": "New York"}
pretty = json.dumps(obj, indent=4, ensure_ascii=False)
print(pretty)
# {
#     "name": "Jane",
#     "age": 25,
#     "city": "New York"
# }

3. Reading and Writing JSON Files

import json

config = {"debug": True, "version": 1.2}
with open('config.json', 'w', encoding='utf-8') as f:
    json.dump(config, f, indent=2, ensure_ascii=False)

with open('config.json', encoding='utf-8') as f:
    loaded = json.load(f)
print(loaded, type(loaded))

4. Exception Handling and Validation

import json

def safe_load(json_str):
    try:
        return json.loads(json_str)
    except json.JSONDecodeError as e:
        print("Parsing error:", e)
        return None

print(safe_load('{"bad json": }'))  # None

Summary

  • Convert JSON strings and Python objects using loads and dumps.
  • Create readable JSON with indent and ensure_ascii=False.
  • Use load and dump for JSON file operations.
  • Handle JSON parsing errors effectively with JSONDecodeError.

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“