Programming

JavaScript: get a JSON answer from AI

Ask for clean JSON with responseMimeType and turn it into an object with JSON.parse.

All lessons · JavaScript lessons: learn from scratch

JSON, not text

Text is enough for a chat. In a quiz, a dictionary and a shop you need the question, the options and the right answer separately. Pulling that out of a long sentence is hard. responseMimeType: "application/json" inside generationConfig forces the AI to return clean JSON. It does not write "Hello, here you go". generationConfig is not inside contents. It sits at the same level.

const sorguMelumati = {
  contents: [{ parts: [{ text: "2 rəng adı və kodu ver." }] }],
  generationConfig: { responseMimeType: "application/json" }
};

JSON.parse and a quiz

The part that arrives is still text, not an object. JSON.stringify turns an object into text so you can send it. JSON.parse turns the text into an array. Write the key names exactly in the question: sual, variantlar, duzgunCavab. If you do not, the AI invents a different name each time. Then you read testler[0].sual and testler[0].duzgunCavab.

const apiKey = process.env.GEMINI_API_KEY;
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`;

async function testYarat(movzu) {
  const telimat = `${movzu} mövzusunda 2 sual hazırla. Massiv qaytar. Hər obyektdə sual, variantlar və duzgunCavab olsun.`;
  const cavab = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      contents: [{ parts: [{ text: telimat }] }],
      generationConfig: { responseMimeType: "application/json" }
    })
  });
  const melumat = await cavab.json();
  const jsonMetni = melumat.candidates[0].content.parts[0].text;
  const testler = JSON.parse(jsonMetni);
  console.log(testler[0].sual, testler[0].duzgunCavab);
}

Questions

Why is sual undefined? JSON.parse was not written. jsonMetni is still text, not an array.

Why does the key change every time? The question has no names. Write the words sual, variantlar and duzgunCavab into the instruction.

Where does generationConfig go? Next to contents, not inside it. The value of responseMimeType is application/json.

What is the difference between stringify and parse? stringify sends. parse turns the arriving text into an object.

Author: Nibras Code