1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JavaScript】 JSONをオブジェクトに変換 parseメソッド

Posted at

JSON.parseメソッドとは?

JSON形式で書かれた文字列をJavaScriptのJSONオブジェクトに変換するメソッドです。
変換した場合は、JavaScriptの中でJSONのデータを自由に扱えるようになります。

書き方

変数 = JSON.parse(変換するJSON [, 関数])

実装例

const json = '{"firstName":"太郎","lastName":"山田"}';

const obj = JSON.parse(json); // =>JSONをJavaScriptのオブジェクトに変換

console.log(obj.firstName); // =>太郎

console.log(obj.lastName); // =>山田

parseメソッドの引数に関数を使用する

以下はキーがfirstNameのとき、値をたろうで返し、それ以外はそのまま返します。
指定したキー(firstName)の値のみが変更されています。

const json = '{"firstName":"太郎","lastName":"山田"}';

const a = JSON.parse(json,(key,value)=>{
	if (key=="firstName") {
		return "たろう" ;
	}
	return value ;
} ) ;

console.log(a); // =>{firstName: "たろう", lastName: "山田"}

#参照
JavaScript | MDN JSON.parse()

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?