How can I pretty-print JSON using node.js?

前端 未结 6 1053
心在旅途
心在旅途 2020-11-28 00:22

This seems like a solved problem but I am unable to find a solution for it.

Basically, I read a JSON file, change a key, and write back the new JSON to the same file

6条回答
  •  情歌与酒
    2020-11-28 00:58

    If you just want to pretty print an object and not export it as valid JSON you can use console.dir().

    It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.

    const jsonString = `{"name":"John","color":"green",
                         "smoker":false,"id":7,"city":"Berlin"}`
    const object = JSON.parse(jsonString)
    
    console.dir(object, {depth: null, colors: true})
    

    Under the hood it is a shortcut for console.log(util.inspect(…)). The only difference is that it bypasses any custom inspect() function defined on an object.

提交回复
热议问题