Module 8 of 10

Structured Output with JSON

Get predictable, parseable responses

📦 Why Structure Matters

Free-form text is great for humans, but terrible for code. JSON gives you predictable, machine-readable output you can parse programmatically.

❌ Unstructured Output:

The product "iPhone 15" costs around $999 and it's really great! It has amazing features like...

Hard to parse, inconsistent format

âś… JSON Output:

{
  "name": "iPhone 15",
  "price": 999,
  "currency": "USD"
}

Easy to parse, consistent!

📝 How to Request JSONOutput

Be explicit! Provide a JSON schema and examples.

Template:

"Extract the following information and return it as JSON:"

{
  "field1": "description",
  "field2": "description"
}

🎯 Real-World Example

PROMPT:

"Extract product information from this text and return as JSON with fields: name, price, rating, inStock (boolean)."

Text: "The Samsung Galaxy S24 is priced at ₹74,999 and has a 4.5 star rating. Currently available in stores."

OUTPUT:

{
  "name": "Samsung Galaxy S24",
  "price": 74999,
  "currency": "INR",
  "rating": 4.5,
  "inStock": true
}

⚡ JSON Best Practices

đź“‹

Always provide a schema

Show exact field names and types

đź’ˇ

Give an example

One example is worth 1000 words

🔢

Specify data types

string, number, boolean, array

⚠️

Handle errors gracefully

Specify what to do with missing data

âś…

Validate the output

Always parse and validate in your code

🚀 Nested JSON (Advanced)

For complex data, use nested objects and arrays:

{
  "restaurant": "Delhi Darbar",
  "location": {
    "city": "Mumbai",
    "area": "Colaba"
  },
  "menu": [
    {"item": "Biryani", "price": 250},
    {"item": "Paneer Tikka", "price": 180}
  ],
  "rating": 4.2,
  "vegetarian": true
}

🎓 Key Takeaways

JSON = predictable, parseable, machine-readable output

Always provide a schema with field names and types

Give at least one example in your prompt

Specify data types: string, number, boolean, array, object

Handle missing data gracefully in your schema

Always validate JSON in your code before using it

Use nested objects and arrays for complex data

Module 8 of 10 Complete