Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to minify a JSON text file with grunt?

I need to minify a set of JSON files (language files) with Grunt/grunt-contrib-uglify:

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
        build: {
            src: 'src/main/app/resources/locales/*/*.json',
            dest: 'target/resources/locales/*/*.json'
        }
    }
});

What I'm getting is:

Files: src/main/app/resources/locales/en/messages.json -> target/*/*.json
Minifying with UglifyJS...Reading src/main/app/resources/locales/en/messages.json...OK
>> Uglifying source "src/main/app/resources/locales/en/messages.json" failed.
Warning: Uglification failed. Use --force to continue.

I'm starting to wonder, does uglify work on pure JSON files, or is it intended for JavaScript source files only? The JSON file is surely well formed, it runs in the application in its non-minimized form.

like image 786
MaDa Avatar asked Sep 30 '13 12:09

MaDa


People also ask

Can JSON be Minified?

Users can also minify the JSON file by uploading the file. Once you have minified JSON Data. User can download it as a file or save it as a link and Share it. JSON Minifier works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.

Why do we minify JSON?

The purpose of the JSON Minifier tool is to minify JSON text, reduce your JSON file size and make it hard to read. JSON (JavaScript Object Notation) is a lightweight data-interchange format, it's useful for exchanging data from client to server, or from server to client.


2 Answers

The grunt-json-minify (as indicated in user2806181's answer) works OK (thanks, by the way), but it only modifies files in place. Inspired by the answer, I've found one that's a bit more advanced: grunt-minjson:

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    minjson: {
        build: {
            files: { 
                'target/locales/en/messages.json':
                    'resource/locales/en/messages.json'
            }
        }
    }
});
like image 176
MaDa Avatar answered Sep 30 '22 21:09

MaDa


I guess UglifyJS does not work on pure JSON, because its not valid javascript.

Take a look at this link: https://github.com/mishoo/UglifyJS2/issues/156

But there are several grunt-plugins you can use, for example: https://npmjs.org/package/grunt-json-minify

like image 22
shry Avatar answered Sep 30 '22 19:09

shry