2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React × Gemini API で `JSON.parse` エラーが出たときの原因と対処法まとめ

Posted at

Gemini API に JSON形式で返すよう指示しても以下のように マークダウン付きのコードブロック で返ってくることがあります。

```json
{
  "word": "take",
  "meaning": "取る、受け取る",
  ...
}

このような「json」や「」が混ざっていると、JSON.parse() ではエラーになります。

発生したエラー例

SyntaxError: Unexpected token '`', "```json\n{...}" is not valid JSON

解決策

1. プロンプトを調整する

const prompt = `
次の英単語「\${input}」について、日本語で以下の形式の**JSON文字列のみ**を返してください。
装飾や説明文、バッククォートなどは含めないでください。

{
  "word": "単語",
  "meaning": "意味",
  "partOfSpeech": "品詞",
  "pronunciation": "発音記号",
  "example": "英語の例文(日本語訳付き)"
}`;

2. 返答をtrimでクリーンアップしてから JSON.parse()する

try {
  const cleaned = rawText?.replace(/```json|```/g, '').trim();
  const parsed = JSON.parse(cleaned || '');
  setParsedResult(parsed);
} catch (e) {
  console.error("JSONパースエラー", e);
  setParsedResult(null);
}

まとめ

Geminiの返答にはMarkdownが混じることがあるため、そのままJSONとして処理するのは難しいことがあります。そこで、プロンプト設計に加えて前処理の工夫が必要になります。

不要な装飾を取り除いたうえで文字列を整えてからJSON.parse()を行うことで、より安全に期待するデータを取り出すことができます。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?