JavaScriptでJSONを読みやすく整形する

公開日: 2018年8月15日GitHub

JavaScriptでJSONをprettifyするには、以下のようにJSON.stringify()の第三引数にインデントに使うスペースの数を指定する。

コード

1const data = {"fruit":"Apple","size":"Large","color":"Red"}
2const pretty = JSON.stringify(data, null, 4)
3console.log(pretty)
4

出力

以下のようにインデント幅4でインデントされて表示される。

1{
2 "fruit": "Apple",
3 "size": "Large",
4 "color": "Red"
5}
6

Reference

MDN - JSON.stringify()

This site uses Google Analytics.
source code