こんにちは。
本日はJavaScriptメモです。
JSON形式の文字列をオブジェクトに変換
JSON形式の文字列をオブジェクトに変換するにはJSON.parse()
を使用します。
引数に、変換したいJSON文字列を指定します。
let json = '{"id": 1, "name": "bob", "color": ["yellow", "red"]}' let obj= JSON.parse(json) console.log(`id = ${obj.id} (${typeof obj.id})`) console.log(`name = ${obj.name} (${typeof obj.name})`) console.log(`color = ${obj.color} (${typeof obj.color})`)
実行結果は以下です。
id = 1 (number) name = bob (string) color = yellow,red (object)
オブジェクトをJSON形式の文字列に変換する
オブジェクトをJSON形式の文字列に変換するにはJSON.stringify()
を使用します。
引数に、変換したいJSON文字列を指定します。
let obj = { id: 1, name: 'bob', color: ['yellow', 'red'] } let json = JSON.stringify(obj) console.log(json)
実行結果は以下です。
{"id":1,"name":"bob","color":["yellow","red"]}
第2引数には、変換用の関数やプロパティ名の配列を指定できます。
特定のkeyを除外する関数を指定してみます。
let obj = { id: 1, name: 'bob', color: ['yellow', 'red'] } let replacer = (k, v) => { if (k === 'color') { return undefined } return v; } let json = JSON.stringify(obj, replacer) console.log(json)
実行結果は以下です。
{"id":1,"name":"bob"}
第3引数には、インデントを指定します。
数値を指定した場合、インデントとして使用する空白の数を意味します。
let obj = { id: 1, name: 'bob', color: ['yellow', 'red'] } let json = JSON.stringify(obj, null, '\t') console.log(json)
実行結果は以下です。
{ "id": 1, "name": "bob", "color": [ "yellow", "red" ] }
以上です。