javascript エラー「TypeError: JSON.stringify cannot serialize cyclic structures.」の解決方法

javascript エラー「TypeError: JSON.stringify cannot serialize cyclic structures.」の解決方法

javascriptで、エラー「TypeError: JSON.stringify cannot serialize cyclic structures.」が発生した場合の原因と解決方法を記述してます。

環境

  • OS macOS Monterey
  • ブラウザ safari 15.5

エラー内容

以下のコードで発生。

let x = {};
let y = {name:'taro',age:20}; 

x.human = y;

console.log(
  JSON.stringify(x) // {"human":{"name":"taro","age":20}}
)

y.human = x;

console.log(
  JSON.stringify(x)
)

エラーメッセージ

TypeError: JSON.stringify cannot serialize cyclic structures.

画像

原因

「y.human = x」したことで、循環参照となっているため

解決方法

以下のように、循環エラーを防ぐ関数を作成して「JSON.stringify」で使用する

let x = {};
let y = {name:'taro',age:20}; 

x.human = y;

console.log(
  JSON.stringify(x) // {"human":{"name":"taor","age":20}}
)

y.human = x;

let arr = []; 

const rep = (key, value) =>{

  if (value != null && typeof value == "object") {
    if (arr.indexOf(value) >= 0)  return;
    arr.push(value);
  }

  return value;

};

console.log(
  JSON.stringify(x,rep)
)

実行結果