添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
11
9

More than 3 years have passed since last update.

JSON.stringifyで`TypeError: Converting circular structure to JSON`というエラーが出た時の対処法

Posted at

オブジェクトをJSON.stringifyしたときに、循環参照が含まれていると以下のようなエラーが出ます。

const a = { a1: "test" };
a.aa = a;
JSON.stringify(a);
TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    --- property 'aa' closes the circle
    at JSON.stringify (<anonymous>)
const { decycle, encycle } = require('json-cyclic');
const a = { a1: "test" };
a.aa = a;
console.log(JSON.stringify(decycle(a)));

json-cyclicは、内部で循環参照を検出したとき、復元ができるようにタグ付けを行い、参照を削除する仕組みです。

オブジェクトを復元したい場合は以下のようにencycleを使います。

const { decycle, encycle } = require('json-cyclic');
const a = {a1: "test"};
a.aa = a;
const json = JSON.stringify(decycle(a));
const obj = JSON.parse(json);
const b = encycle(obj);
console.log(b);
console.log(b.aa.aa.aa.a1);

ちゃんと復元できることが確認できました。

11
9
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
11
9