wawoon blog

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

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

コード

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

出力

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

{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red"
}

Reference

MDN - JSON.stringify()