Nested Objects and Arrays
You'll learn how to work with complex, multi-level data structures when using JSON mode and function calling to get structured output from LLMs.
What Are Nested Structures?
Real-world data rarely stays flat. A customer order might contain multiple items, each with properties. A company profile might include an array of employees, each with their own nested address. Nested objects and arrays let you represent this hierarchical data naturally in JSON.
Think of it like Russian nesting dolls: one structure contains another, which might contain yet another. In JSON:
- Nested objects are objects inside objects (
{ "user": { "address": { "city": "NYC" } } }) - Arrays hold lists of items (
{ "items": ["apple", "banana"] }) - Arrays of objects combine both (
{ "orders": [{ "id": 1, "total": 50 }] })
Why This Matters for Structured Output
When defining function schemas or prompting for JSON mode, you need to specify these nested structures clearly. The LLM must understand not just that you want a list, but that each list item contains specific fields, or that an object property itself contains another object with its own schema.
For example, if you're extracting information about books from text, you might want:
- A
booksarray - Each book with
title,author, andreviews - Each review as a nested object with
ratingandcomment
The LLM needs your schema to know exactly how deep and complex to make the structure.
Key Takeaway: Nested objects and arrays let you capture complex, hierarchical real-world data in structured LLM outputs—you must define these multi-level schemas clearly in your function definitions or prompts.