JSON を検証する方法
文字列が有効な JSON かどうかをチェックし、構文エラーとその場所を特定します。
问题
信頼できないソースや手作業で編集された JSON 文字列があり、構文的に正しいことを確認する必要があります。
前提条件
- JSON 構文の理解
- エラーメッセージを読めること
ステップ
-
1. Parse the JSON string
Attempt to parse the string as JSON. A standards-compliant parser will throw an error if the syntax is invalid. Common errors include trailing commas, single-quoted strings, and missing brackets.
入力{"name":"John",}输出Error: Unexpected token } at position 15 -
2. Interpret the error location
If parsing fails, the error message typically includes the position or line number of the problem. Go to that location in the input and fix the syntax issue. Repeat until parsing succeeds.
入力position 15输出trailing comma before } -
3. Optionally validate against a schema
If you have a JSON Schema, validate the parsed JSON against it to check not just syntax but structure (required fields, types, value ranges). Schema validation catches semantic errors that syntax parsing cannot.
入力JSON + schema输出valid or schema errors
期待される結果
JSON が有効であることの確認、または問題とその場所を特定する明確なエラーメッセージ。
よくあるエラー
- Trailing comma in object or array
- JSON does not allow trailing commas. Remove the comma after the last element.
- Single-quoted strings
- JSON requires double quotes for strings and keys. Replace single quotes with double quotes.
トラブルシューティング指引
- If the error position seems wrong, check for invisible characters like BOM or zero-width spaces.
- Use a JSON validator with line and column numbers for easier debugging.
セキュリティ上の制限
- Parsing untrusted JSON is generally safe, but do not use eval() to parse JSON — it can execute arbitrary code. Use JSON.parse instead.