javascriptjsonnode.jsminifyuglifyjs2

UglifyJs JavaScript API for JSON minification?


So I am looping through files in a directory via Node and want to minify them with UglifyJs.

The API is dead easy for JavaScript files:

var UglifyJS = require("uglify-js")

// Looping here
UglifyJS.minify(listOfAllFiles[i])

However, the files I need to minify are JSON files, so this is producing an eval error. In the command line, if you are minifying JSON, you just pass --expr and it will evaluate as a single expression. Any idea how to pass this into the options object of the JavaScript API?

Cheers.


Solution

  • If you're not dead set on UglifyJS, you could solve this with plain JavaScript, because JSON can't really be uglified that much. To remove all whitespace, use:

    JSON.stringify(JSON.parse(listOfAllFiles[i]))
    

    (Assuming listOfAllFiles[i] is the JSON string.)