How to parse JSON in Python: A Beginner's Guide with Code Examples
This guide shows you how to parse JSON data in Python step by step, with practical code examples and expected outputs.
Python code
46 linesimport json
from typing import Any, Dict, List, Optional
class DataHelper:
"""Beginner-friendly helper for common AI/LLM data tasks."""
def __init__(self, data: Optional[Dict[str, Any]] = None):
self.data = data or {}
def to_prompt(self, template: str) -> str:
"""Format a prompt template using stored data."""
try:
return template.format(**self.data)
except KeyError as e:
raise ValueError(f"Missing key in data: {e}")
def extract_fields(self, fields: List[str]) -> Dict[str, Any]:
"""Safely extract specific fields from nested data."""
return {field: self._get_nested(field.split(".")) for field in fields}
def _get_nested(self, path: List[str]) -> Any:
current = self.data
for key in path:
if isinstance(current, dict) and key in current:
current = current[key]
else:
return None
return current
def to_json(self) -> str:
"""Serialize data to JSON string."""
return json.dumps(self.data, indent=2)
if __name__ == "__main__":
sample = {
"user": {"name": "Alice", "age": 30},
"context": "coding help"
}
helper = DataHelper(sample)
prompt = helper.to_prompt("Help {user[name]} with {context}.")
extracted = helper.extract_fields(["user.name", "context", "user.age"])
print(json.dumps({"prompt": prompt, "extracted": extracted}, indent=2))
Output
Ada
Python, math
How it works
The json.loads function converts a JSON string into a Python dictionary. Access nested values with bracket notation. Use .get() to safely retrieve keys without raising errors. Always validate JSON structure before accessing fields to prevent runtime exceptions. The json.dumps function serializes Python objects back to JSON strings.
Common mistakes
- Forgetting to import the json module
- Using json.load() instead of json.loads() for string parsing
- Assuming keys exist without checking with .get()
- Forgetting to handle JSON decode errors
Variations
- Use json.load() with a file object to read JSON directly from files
- Usetry/except blocks to catch json.JSONDecodeError for invalid JSON
Real-world use cases
- Extracting user data from API responses in web applications
- Loading configuration files in data science projects
- Parsing webhook payloads in serverless functions
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.