j_d
j_d

Reputation: 3082

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.

Upvotes: 2

Views: 6543

Answers (2)

Daniel Diekmeier
Daniel Diekmeier

Reputation: 3434

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.)

Upvotes: 12

Bean
Bean

Reputation: 21

UglifyJS doesn't minify JSON.

You can minify using jsonminify instead.

Contrary to what others are saying, JSON minification is useful, as it allows you to use comments in JSON (which are not allowed in .json files).

Upvotes: 2

Related Questions