LoginSignup
5
2

More than 3 years have passed since last update.

JSON.parse() しても 文字列 が返ってくる問題を調べた話

Last updated at Posted at 2019-06-02

経緯と問題

こんな感じのコードを書いていた

const test_data = '{ "id": 1, "comment": "foo" }';
const str = JSON.stringify(test_data);
const myobj = JSON.parse(str);
console.log(typeof myobj) // 期待 : object, 結果 : string

ここで出力されるのは object を期待。
しかし実際は string でした。

忙しい方への オチ はこちら。

実験

ぐぐったらこんな記事が。
2回 JSON.parse() するの?

あ、マジでうまくいった。

const test_data = '{ "id": 1, "comment": "foo" }';
const str = JSON.stringify(test_data);
const not_obj_str = JSON.parse(str);
const myobj = JSON.parse(not_obj_str);
console.log(typeof obj) // 期待 : object, 結果 : object

原因

const test_data = '{ "id": 1, "comment": "foo" }';
const str = JSON.stringify(test_data);

ダメだったのはここ。
すでに文字列な状態のものに (輪をかけて) JSON.stringify() してしまっていた。

JSON の完全な構文は以下のとおりです に続く定義に書かれている通り、
文字列を文字列にするみたいなのは別におかしくなさそう。

JSONString = ""
          or " StringCharacters "

(個人的には、文字列が入ったら「文字列を文字列にするの? 意味なくね?」的なエラーが来ると思っていた...)
stringify の箇所だけ try-catch しても普通に動くのは確認済み。

最終的な対応

const testData = { "id": 1, "comment": "foo" };
const str = JSON.stringify(test_data);
const myobj = JSON.parse(str);
console.log(typeof myobj) // 期待 : object, 結果 : object

もちろん、 そもそもの入力として、素直にJSONを入れればよいです。
あたり前田のクラッカー。

実験と余談

const test_data = '{ "id": 1, "comment": "foo" }';
const str = JSON.stringify(test_data);
const str_two = JSON.stringify(str);
const myobj = JSON.parse(str_two);
const myobj_two = JSON.parse(myobj);
const myobj_three = JSON.parse(myobj_two);
console.log(typeof myobj_three); //object

例外が出力されない。うーむ、そういうものかー。

参考文献

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

5
2
1

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