How to beautify/prettify a Json/JS file in a node.js script

感情迁移 提交于 2019-12-02 02:27:33

问题


I am searching a way to prettify Json files in a node.js script (not CLI). I found a lot of npm beautifier packages, but none that can simply beautify directly a file.

There is esbeautifier that do what I am searching to do, but the exemples only shows CLI commands: https://github.com/royriojas/esbeautifier Is there a way to use it in a Javascript?


回答1:


you can use the tool esformatter.

edit by @jck: here is JS snippet that works using fs:

var esformatter = require('esformatter');
var fs = require('fs');
var filename = "./myFile.json";
var codeStr = fs.readFileSync(filename).toString();
var formattedCode = esformatter.format(codeStr);
fs.writeFile(filename, formattedCode);



回答2:


You can prettyprint JSON easily by providing parameters to JSON.stringify().

Many people use this kind of call to prettyprint JSON output. It's still valid JSON, it just contains indentation and newlines.

 JSON.stringify(myObject, null, 2);



回答3:


Alternatively, check out prettyjson! It has been great for me!



来源:https://stackoverflow.com/questions/39359638/how-to-beautify-prettify-a-json-js-file-in-a-node-js-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!