2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSON.parseのreviverで項目が消える理由:return忘れと配列の穴をNode.jsで実測

2
Posted at

JSON.parse() で項目が消えたら、reviver の戻り値を確認します。

第2引数の reviver が undefined を返すと、そのプロパティは削除されます。対象外では元の値を返します。

検証環境は macOS 27.2.1 / Node.js v24.22.1。以下の JavaScript を実行しました。ブラウザと Windows では試していません。

変換しない項目にも return が必要

日付だけ変換する例です。

const json = '{"name":"メモ","createdAt":"2026-11-18T00:00:00Z"}';
const broken = JSON.parse(json, (key, value) => {
  if (key === 'createdAt') return new Date(value);
});
console.log(broken);
undefined

何も返さない経路は undefined を返すため、全体も消えました。

対象外も値を返します。

const json = '{"name":"メモ","createdAt":"2026-11-18T00:00:00Z"}';
const fixed = JSON.parse(json, (key, value) => {
  if (key === 'createdAt') return new Date(value);
  return value;
});
console.log(fixed.name);
console.log(fixed.createdAt instanceof Date);
console.log(fixed.createdAt.toISOString());
メモ
true
2026-11-18T00:00:00.000Z

最後は解析結果全体にも呼ばれる

reviver は子の値から処理し、その後に親へ進みます。最後は、空文字列のキーで解析結果全体を受け取ります。

const calls = [];
JSON.parse('{"user":{"name":"メモ"}}', (key, value) => {
  calls.push(key);
  return value;
});
console.log(JSON.stringify(calls));
["name","user",""]

最初の例も、最後に元の値を返さないため全体が消えます。

配列の削除は「前へ詰める」ではない

undefined を返して配列の要素を削除しても、前へ詰まりません。

const values = JSON.parse('[1,2,3]', (key, value) => {
  return value === 2 ? undefined : value;
});
console.log(values.length);
console.log(Object.hasOwn(values, 1));
console.log(JSON.stringify(values));
3
false
[1,null,3]

長さは3のままで、インデックス1が欠けています。JSON.stringify() で見える null は、配列に実際の null が入っているという証拠にはなりません。ここでは穴が JSON 化の際に null として出力されています。

前へ詰めるなら、解析後に filter() を使えます。

const compact = JSON.parse('[1,2,3]').filter(value => value !== 2);
console.log(JSON.stringify(compact));
[1,3]

確認する経路

AI のコードでは対象外の経路にも return value があるか点検します。日付変換は最小例なので、本番では型や有効性の確認も必要です。空文字列のキーは JSON 内にも存在し得るため、全体判定に決め打ちしません。以前の JSON 保存・数値精度の記事と異なり、今回は解析後の変換が対象です。

仕様の根拠は ECMAScript の InternalizeJSONProperty です。undefined による削除処理が定義されています。


未経験者向けの体験版を公開しています

※ 中上級者には易しすぎる内容なので、初心者の知り合いへの紹介や社内研修の参考としてどうぞ。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?