LoginSignup
37
37

More than 5 years have passed since last update.

JavaScriptでJSONを扱う時のメモ

Posted at

JSONとは

JavaScript Object Notationの省略がJSON。
ちなみにNotationとは、『記法』という意味。
JavaScriptオブジェクト構文の記法をベースに作られている為、JavaScriptという文言を含んでいる。
テキストベースのフォーマットでデータ構造を表現している。

JSONをパース(parse)するとは?

JSONを扱っていてよく耳にするのが、『パース(parse)する』という表現。
結論から言うと、この意味は『JSONを解析する、JSONを読み込む』といったニュアンスで使われます。

JavaScriptでの利用

JavaScriptでJSONを扱う場合は、ビルドイン関数を利用できます。
JSON形式の文字列とJavaScriptを相互変換のための関数は以下の二つ。

  • parse
  • stringify

JSON→JavaScriptオブジェクトにする

JSONをJavaScriptオブジェクトに変換するには、parseを使う。
参考はこちら

// 基本構文
JSON.parse(text[, reviver])

const json = '{"result": true, "count": 30}';
const obj = JSON.parse(json);

console.log(obj.result);
console.log(obj.count);

JavaScriptオブジェクト→JSON

JavaScriptのオブジェクトをJSONに変換するには、stringfyを使う。
参考はこちら

// 基本構文
JSON.stringify(value[, replacer[, space]])

const obj = {result: true, count: 30};
const json = JSON.stringify(obj);

console.log(json);

参考

37
37
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
37
37