/06. Structured JSON Outputs

    06. Structured JSON Outputs

    Explanation

    By forcing the AI into JSON mode using `responseMimeType`, we eliminate the risk of the model adding conversational fluff like "Here is the JSON you requested...". This is essential for programmatic use cases—for example, generating dummy data for a database or extracting entities from an unstructured document.

    Example

    const response = await ai.models.generateContent({
      model: 'gemini-2.5-flash',
      contents: 'Give me a JSON object with a "name" and "age" field.',
      config: {
        responseMimeType: 'application/json'
      }
    });

    Exercise Task

    When building applications, you often need the AI to return parsable data (like JSON) instead of raw conversational text. **Step 1.** Ask the AI to generate details for a famous sci-fi movie (Title, Director, Year). **Step 2.** Pass the `config: { responseMimeType: 'application/json' }` option alongside the model and contents. **Step 3.** Log the result. Try doing `JSON.parse(response.text)` to prove it's valid data!

    script.js
    Console

    Click "Run" to execute your code...

    🍪 We Value Your Privacy

    We use cookies to enhance your browsing experience, serve personalized ads or content, and analyze our traffic. By clicking "Accept All", you consent to our use of cookies according to our Privacy Policy.

    Learn More