for (const text of ['', '{"a":', '[1,', '{']) {
try {
JSON.parse(text);
} catch (error) {
console.log(JSON.stringify(text), '->', error.message);
}
}
出力書き換えて実行できます
Ctrl+Enter でも実行JS · UTF-8
"" -> Unexpected end of JSON input
"{\"a\":" -> Unexpected end of JSON input
"[1," -> Unexpected end of JSON input
"{" -> Expected property name or '}' in JSON at position 1 (line 1 column 2)
functiondiagnose(text) {
const head = text.trim().slice(0, 20);
if (head === '') return'本文が空';
if (head.startsWith('<')) return'HTML が返っている(通信を疑う)';
if (head.includes("'")) return'単引用符がある(JSON では使えない)';
return'中身を確かめる: ' + head;
}
console.log(diagnose(''));
console.log(diagnose('<!DOCTYPE html>'));
console.log(diagnose("{'a':1}"));
console.log(diagnose('{"a":1}'));
出力書き換えて実行できます
Ctrl+Enter でも実行JS · UTF-8
本文が空
HTML が返っている(通信を疑う)
単引用符がある(JSON では使えない)
中身を確かめる: {"a":1}
読むのは一度だけにして、文字列から組み立ててください。
example.js
for (const text of ['{"name":"あ', '{"name":"あ"', '{"a":1,', '{"a":1']) {
try {
JSON.parse(text);
} catch (error) {
console.log(JSON.stringify(text), '->', error.message);
}
}
出力書き換えて実行できます
Ctrl+Enter でも実行JS · UTF-8
"{\"name\":\"あ" -> Unterminated string in JSON at position 10 (line 1 column 11)
"{\"name\":\"あ\"" -> Expected ',' or '}' after property value in JSON at position 11 (line 1 column 12)
"{\"a\":1," -> Expected double-quoted property name in JSON at position 7 (line 1 column 8)
"{\"a\":1" -> Expected ',' or '}' after property value in JSON at position 6 (line 1 column 7)
この例は通信を伴うので、このページでは実行できません。形だけ示しています。
原因3: JSON ではないものが返ってきた
サーバーがエラー画面(HTML)を返していることがあります。
example.js
const name = 'あ"い';
console.log(JSON.stringify({ name }));
console.log(JSON.parse(JSON.stringify({ name })));
出力書き換えて実行できます
Ctrl+Enter でも実行JS · UTF-8
{"name":"あ\"い"}
{ name: 'あ"い' }
example.js
for (const text of [' ', '\n', '\t']) {
try {
JSON.parse(text);
} catch (error) {
console.log(JSON.stringify(text), '->', error.message);
}
}
出力書き換えて実行できます
Ctrl+Enter でも実行JS · UTF-8
" " -> Unexpected end of JSON input
"\n" -> Unexpected end of JSON input
"\t" -> Unexpected end of JSON input