コンテンツにスキップ

JSONの構造を指定する

JSONの構造を指定する

OpenAI APIのレスポンスで返されるJSONの構造を指定する方法を学びます。

次のように index.html、style.css、main.js の3つのファイルを作成してください。

./works
└── specify-json-structure
├── index.html
├── style.css
└── main.js

Structured Outputs機能を使って、AIが返すレスポンスのJSON構造を指定します。これにより、常に一貫したデータ構造で結果を受け取ることができます。

この例では、ユーザーが入力した説明に基づいて、架空の人物のプロフィール(名前、年齢、出身地、好きなもの)を生成します。

このセクションでは、3段階に分けて実装します:

  1. 第1段階: UIの実装 - APIキーなしでUIの動作確認
  2. 第2段階: 普通のAPI呼び出し - JSON構造を指定しないAPI呼び出し
  3. 第3段階: JSON構造指定 - Structured Outputsでデータ構造を保証

まず、OpenAI APIを使わずにUIの基本構造を作ります。

index.html
1
<html>
2
<head>
3
<title>JSONの構造を指定する</title>
4
<link rel="stylesheet" href="./style.css" />
5
</head>
6
<body>
7
<h1>JSONの構造を指定する</h1>
8
<div>
9
<input type="text" id="descriptionInput" placeholder="どんな人がいいか入力してください" />
10
<button id="generateButton">生成</button>
11
</div>
12
<div id="result">
13
<h2>生成されたプロフィール</h2>
14
<p>名前: <span id="name">-</span></p>
15
<p>年齢: <span id="age">-</span></p>
16
<p>出身地: <span id="hometown">-</span></p>
17
<p>好きなもの: <span id="favorites">-</span></p>
18
</div>
19
<script src="./main.js"></script>
20
</body>
21
</html>
  • input#descriptionInput: プロフィールの説明を入力
  • button#generateButton: プロフィール生成ボタン
  • span#name, span#age, span#hometown, span#favorites: 生成されたプロフィール情報を表示
style.css
1
input[type="text"] {
2
width: 300px;
3
padding: 8px;
4
font-size: 14px;
5
}
6
7
button {
8
padding: 8px 16px;
9
font-size: 14px;
10
cursor: pointer;
11
}
main.js
1
const descriptionInput = document.getElementById('descriptionInput');
2
const generateButton = document.getElementById('generateButton');
3
const nameElement = document.getElementById('name');
4
const ageElement = document.getElementById('age');
5
const hometownElement = document.getElementById('hometown');
6
const favoritesElement = document.getElementById('favorites');
7
8
function showResult(profile) {
9
nameElement.textContent = profile.name;
10
ageElement.textContent = profile.age;
11
hometownElement.textContent = profile.hometown;
12
favoritesElement.textContent = profile.favorites.join(', ');
13
}
14
15
generateButton.addEventListener('click', () => {
16
// 仮のプロフィールデータ
17
const fakeProfile = {
18
name: '仮太郎',
19
age: 25,
20
hometown: '東京都',
21
favorites: ['読書', '映画', '旅行']
22
};
23
24
showResult(fakeProfile);
25
});
  1. DOM要素の取得: 入力欄、ボタン、結果表示エリアを取得
  2. showResult関数: プロフィールデータを画面に表示する関数
  3. イベントリスナー: 仮のプロフィールデータを表示(まだAPIは呼び出していない)

ブラウザでHTMLファイルを開き、以下を確認します:

  1. 入力欄とボタンが表示される
  2. 「生成」ボタンをクリックすると、仮のプロフィールが表示される
↗ 新しいタブで開く
第1段階: 仮のプロフィールを表示する

第1段階で作成したUIに、OpenAI APIを統合します。ただし、まだJSON構造は指定しません。

HTMLは第1段階と同じです(変更なし)。

main.js
1
const OPENAI_API_KEY = 'YOUR_API_KEY_HERE';
2
1
3
const descriptionInput = document.getElementById('descriptionInput');
2
4
const generateButton = document.getElementById('generateButton');
3
5
const nameElement = document.getElementById('name');
main.js
12
14
favoritesElement.textContent = profile.favorites.join(', ');
13
15
}
14
16
15
generateButton.addEventListener('click', () => {
16
// 仮のプロフィールデータ
17
const fakeProfile = {
18
name: '仮太郎',
19
age: 25,
20
hometown: '東京都',
21
favorites: ['読書', '映画', '旅行']
22
};
17
generateButton.addEventListener('click', async () => {
18
const description = descriptionInput.value || 'ランダムな人';
23
19
24
showResult(fakeProfile);
20
const response = await fetch('https://api.openai.com/v1/chat/completions', {
21
method: 'POST',
22
headers: {
23
'Content-Type': 'application/json',
24
'Authorization': `Bearer ${OPENAI_API_KEY}`
25
},
26
body: JSON.stringify({
27
model: 'gpt-6-luna',
28
messages: [
29
{
30
role: 'user',
31
content: `${description}のプロフィール(名前、年齢、出身地、好きなもの)をJSON形式で生成してください`
32
}
33
]
34
})
35
});
36
37
const data = await response.json();
38
const aiMessage = data.choices[0].message.content;
39
40
// JSONっぽい文字列をパースする(エラーが起きる可能性あり)
41
const result = JSON.parse(aiMessage);
42
43
showResult(result);
25
44
});
  1. APIキーの追加: OPENAI_API_KEY定数を追加
  2. fetch APIでリクエスト送信: OpenAI APIを呼び出す
  3. プロンプトの工夫: 「JSON形式で生成してください」と指示
  4. レスポンスのパース: JSON.parse()で文字列をJSONに変換

JSON構造が保証されない問題があります:

  • AIが必ずしもパース可能なJSONを返すとは限らない
  • フィールド名が異なる場合がある(name vs 名前)
  • 必須フィールドが欠けている場合がある
  • 余計な説明文が含まれている場合がある

これらの問題を解決するのが、次の第3段階です。

  1. OPENAI_API_KEYを実際のAPIキーに置き換える
  2. ブラウザでHTMLファイルを開く
  3. 入力欄に説明を入力(例: “明るくて元気な人”)
  4. 「生成」ボタンをクリック
  5. プロフィールが表示されることを確認(エラーが出る可能性もあり)

第2段階のコードに、Structured Outputs機能を追加して、確実に決まった構造のJSONを取得します。

HTMLは第1段階と同じです(変更なし)。

main.js
28
28
messages: [
29
29
{
30
30
role: 'user',
31
content: `${description}のプロフィール(名前、年齢、出身地、好きなもの)をJSON形式で生成してください`
31
content: `${description}のプロフィールを生成してください`
32
32
}
33
]
33
],
34
response_format: {
35
type: 'json_schema',
36
json_schema: {
37
name: 'person_profile',
38
strict: true,
39
schema: {
40
type: 'object',
41
properties: {
42
name: {
43
type: 'string',
44
description: '名前'
45
},
46
age: {
47
type: 'number',
48
description: '年齢'
49
},
50
hometown: {
51
type: 'string',
52
description: '出身地'
53
},
54
favorites: {
55
type: 'array',
56
description: '好きなもののリスト',
57
items: {
58
type: 'string'
59
}
60
}
61
},
62
required: ['name', 'age', 'hometown', 'favorites'],
63
additionalProperties: false
64
}
65
}
66
}
34
67
})
35
68
});
36
69
37
70
const data = await response.json();
38
const aiMessage = data.choices[0].message.content;
71
const result = JSON.parse(data.choices[0].message.content);
39
72
40
// JSONっぽい文字列をパースする(エラーが起きる可能性あり)
41
const result = JSON.parse(aiMessage);
42
43
73
showResult(result);
44
74
});
  1. response_formatの追加: JSON構造を指定する新しいパラメータ
  2. プロンプトの簡略化: 「JSON形式で」という指示が不要になった

response_formatパラメータで、レスポンスのJSON構造を厳密に指定します:

response_format: {
type: 'json_schema',
json_schema: {
name: 'person_profile',
strict: true,
schema: {
type: 'object',
properties: {
name: { type: 'string', description: '名前' },
age: { type: 'number', description: '年齢' },
hometown: { type: 'string', description: '出身地' },
favorites: {
type: 'array',
description: '好きなもののリスト',
items: { type: 'string' }
}
},
required: ['name', 'age', 'hometown', 'favorites'],
additionalProperties: false
}
}
}

主要なフィールド:

  • type: 'json_schema': Structured Outputsを使用
  • name: スキーマの名前(任意)
  • strict: true: 厳密なスキーマ検証を有効化
  • schema: JSONスキーマの定義
    • type: 'object': オブジェクト型
    • properties: 各フィールドの型と説明
    • required: 必須フィールドのリスト
    • additionalProperties: false: 定義外のフィールドを禁止

AIからの返答は必ず指定した構造になります:

const result = JSON.parse(data.choices[0].message.content);

返答例:

{
"name": "田中太郎",
"age": 28,
"hometown": "東京都",
"favorites": ["読書", "映画鑑賞", "旅行"]
}
  1. OPENAI_API_KEYを実際のAPIキーに置き換える
  2. ブラウザでHTMLファイルを開く
  3. 入力欄に説明を入力(例: “明るくて元気な人”)
  4. 「生成」ボタンをクリック
  5. 構造化されたプロフィールが確実に表示されることを確認
  1. 一貫性: 常に同じ構造のデータが返される
  2. 型安全性: 数値、文字列、配列などの型が保証される
  3. エラー削減: パース失敗やフィールド欠落がない
  4. 開発効率: レスポンス処理のコードがシンプルになる
  5. プロンプト簡略化: 「JSON形式で」などの指示が不要

この節を終えたときのディレクトリ

Section titled “この節を終えたときのディレクトリ”
この節を終えたときのファイル