javascript エラー「SyntaxError: Unexpected token o in JSON at position 1」の解決方法

javascript エラー「SyntaxError: Unexpected token o in JSON at position 1」の解決方法

JSON.parse実行時に、エラー「SyntaxError: Unexpected token o in JSON at position 1」の解決方法を記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.114

エラー内容

以下のコードを実行時に発生

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>

async function jsonGet() {
    try {

      const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
      
      const hoge = JSON.parse(res.data);

    } catch (err) {

      console.error(err);

    }
  }

jsonGet()

</script>

jsonデータ

エラーメッセージ(chrome 103.0.5060.114)

SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at jsonGet

エラーメッセージ(firefox 102)

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

原因

文字列が「” (ダブルクォート)」で囲まれていないため発生してます。

const json = '{ a : 100, b : 200, c : 300 }';
const obj = JSON.parse(json);
// Uncaught SyntaxError: Unexpected token a in JSON at position 2

ダブルクォートで囲むとエラーにはなりません。

const json = '{ "a" : 100, "b" : 200, "c" : 300 }';
const obj = JSON.parse(json);

解決方法

一度、JSON.stringifyを使用して文字列化してから、JSON.parseする

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>

async function jsonGet() {
    try {

      const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
      
      const hoge = JSON.parse(JSON.stringify(res.data));

    } catch (err) {

      console.error(err);

    }
  }

jsonGet()

</script>

JSON.stringify後の「json」は以下となります。