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
1
2
3
4
5
6
7
8
9
10
import { GoogleGenAI } from 'https://esm.
sh/@google/genai';
const ai = new GoogleGenAI({ apiKey:
'PASTE_YOUR_API_KEY_HERE' });
async function getMovieJSON() {
// Generate JSON content
}
getMovieJSON();
Console
Click "Run" to execute your code...