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.

Easy Python 3.8+ Aug 9, 2026 AI & LLM integration patterns 14 views 0 copies

Python code

46 lines
Python 3.8+
import 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

stdout
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

  1. Use json.load() with a file object to read JSON directly from files
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.