ものづくりのブログ

うちのネコを題材にしたものづくりができたらいいなと思っていろいろ奮闘してます。

【JavaScript】json を扱ってみる

JavaScript で json を扱う方法をここにメモします。

サンプル

JSON.parse() メソッド

コード

JSON.parse() メソッドは文字列を JSON として解析し、文字列によって記述されている JavaScript の値やオブジェクトを構築します。

$ cat test.js 
const json = '{"result":true, "count":42, "foo": "bar"}';
const obj = JSON.parse(json);

console.log(obj.count);
console.log(obj.result);
console.log(obj.foo);
console.log(obj);
実行結果
$ node test.js 
42
true
bar
{ result: true, count: 42, foo: 'bar' }

JSON.stringify() メソッド

コード

JSON.stringify() メソッドは、ある JavaScript のオブジェクトや値を JSON 文字列に変換します。

$ cat test2.js 
console.log(JSON.stringify({ x: 1, y: 2, z:3 }));
実行結果
$ node test2.js 
{"x":1,"y":2,"z":3}