JSON Processing

MEDIUM2 min readby AdminJune 20, 2026History
0.0|0 ratingsLog in to rate

JSON (JavaScript Object Notation) is a lightweight data-interchange format. In Python, JSON operations are managed via the built-in `json` module (using functio...

#ai-engineering#course#json

Definition

JSON (JavaScript Object Notation) is a lightweight data-interchange format. In Python, JSON operations are managed via the built-in json module (using functions like dumps, loads, dump, and load).

Why It Exists

LLM structured output APIs (like tool calling or JSON mode) return text representations of structured objects. To use this output in application logic, AI Engineers must serialize Python structures to JSON strings and deserialize incoming LLM JSON strings back into Python dictionaries and models.

How It Works

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
JSON PIPELINE
                  ┌─────────────────┐
                  │ Python Dict/Obj │
                  └────────┬────────┘
                           │
       Serialize           │          Deserialize
     (json.dumps) ─────────┼────────► (json.loads)
                           │
                  ┌────────▼────────┐
                  │   JSON String   │ (Text representation)
                  └─────────────────┘

* **Serialization**: Converting Python structures (dict, list, str) into a JSON string format using `json.dumps()` or saving to a file using `json.dump()`.
* **Deserialization**: Parsing a JSON string back into a Python dict or list using `json.loads()` or reading from a file using `json.load()`.

Real-World Example

Example

ChatGPT Actions or plugins use JSON to pass parameters (e.g., {"location": "San Francisco", "units": "celsius"}) between the LLM model and external API endpoints.

Python Example

Example

Here is a production-grade parser that extracts, parses, and validates JSON blocks nested inside raw LLM markdown responses:

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import json
from typing import Dict, Any, Optional

def extract_and_parse_llm_json(raw_output: str) -> Optional[Dict[str, Any]]:
    """
    Extracts and parses a JSON block from a raw text output, 
    even if wrapped in markdown code fence blocks.
    """
    # Clean output and extract text between markdown code fences
    cleaned = raw_output.strip()
    if "```json" in cleaned:
        cleaned = cleaned.split("```json")[1].split("```")[0].strip()
    elif "```" in cleaned:
        cleaned = cleaned.split("```")[1].split("```")[0].strip()
        
    try:
        return json.loads(cleaned)
    except json.JSONDecodeError as e:
        print(f"JSON parsing failed: {e}. Check formatting inside: {cleaned}")
        return None

# Demo
if __name__ == "__main__":
    llm_markdown_response = """
    Here is the requested output format:
    ```json
    {
        "agent_name": "ReviewerBot",
        "approved": true,
        "score": 9.5
    }
    ```
    I hope this helps!
    """
    parsed_data = extract_and_parse_llm_json(llm_markdown_response)
    print("Parsed JSON Map:", parsed_data)

Interview Questions

  • Beginner: What is the difference between json.loads and json.dumps?
  • Intermediate: What is the difference between json.load and json.loads?
  • Advanced: How do you serialize a custom Python class (like a Dataclass or custom object) that the standard json module doesn't recognize out of the box?

Interview Answers

  • Beginner: json.loads parses a JSON-formatted string and converts it into a Python dictionary or list. json.dumps takes a Python dictionary or list and serializes it into a JSON-formatted string.
  • Intermediate: The trailing "s" stands for "string". json.loads and json.dumps operate on JSON strings, whereas json.load and json.dump operate on JSON files (file-like objects).
  • Advanced: Customize the serialization behavior by subclassing json.JSONEncoder and overriding the default() method to convert the custom object into a serializable representation (like a dictionary), then pass this custom encoder class to the json.dumps(obj, cls=MyEncoder) call.

Common Mistakes

  • Assuming raw LLM output is valid JSON: LLMs regularly miss closing brackets or append trailing text. Always wrap your parsing code in try-except json.JSONDecodeError blocks.

Assignment

Write a script that takes a python dictionary containing a nested list, serializes it to a string with indentation set to 4 spaces, and prints the result.


Discussion

Join the discussion! Sign in to leave comments and ask questions.

Loading discussion...