11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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);
実行結果
JSON.stringify(a);
     ^

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    --- property 'aa' closes the circle
    at JSON.stringify (<anonymous>)

対処法

json-cyclicを使えば解決します。

json-cyclic - npm
https://www.npmjs.com/package/json-cyclic


npm install json-cyclic
コード
const { decycle, encycle } = require('json-cyclic');

const a = { a1: "test" };
a.aa = a;
console.log(JSON.stringify(decycle(a)));
実行結果
{"a1":"test","aa":{"$ref":"$"}}

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);
実行結果
{ a1: 'test', aa: [Circular] }
test

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

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?