Compile JSON files into Javascript Tutorial

Just a quick tutorial on how to compile JSON files into a single JavaScript file. This is very easy with GruntJS and the grunt-json plugin.

Grunt JS Setup

If you have never used GruntJS before you probably need to checkout my Install Grunt JS on a Mac Tutorial or Install Grunt JS on Windows Tutorial.

Example Code

To follow along with this tutorial you may want to download the files from https://github.com/codeBelt/Example-JSON-to-Javascript and click the “Download Zip” button.

Grunt File

If you take a look at the json config area you will see some options. Those options are:

namespace
The namespace in which the json data will be assigned. (Default: ‘myjson’)
includePath
Includes the full path of the file and the extension. By default only the file name is used as the key value. (Default: false)
processName
This option accepts a function which takes one argument (filename) and returns a string which will be used as the key for the object. The example below stores all json data on the default JSON_DATA namespace in lowercase letters. (Default: null)
module.exports = function(grunt) {

    // Project configuration.
    grunt.initConfig({

        //Read the package.json (optional)
        pkg: grunt.file.readJSON('package.json'),

        // Constants for the Gruntfile so we can easily change the path for
        // our environments.
        BASE_PATH: '../',
        DEVELOPMENT_PATH: '../dev/',
        PRODUCTION_PATH: '../prod/',

        // The JSON to JavaScript plugin.
        json: {
            prod: {
                options: {
                    namespace: 'JSON_DATA',
                    includePath: false,
                    processName: function(filename) {
                        return filename.toLowerCase();
                    }
                },
                src: ['<%= DEVELOPMENT_PATH %>' + '**/*.json'],
                dest: '<%= PRODUCTION_PATH %>' + 'assets/scripts/json.js'
            }
        }

    });

    // Loads the necessary tasks for this Grunt file.
    grunt.loadNpmTasks('grunt-json');

    // Grunt tasks.
    grunt.registerTask('default', ['json']);

};

Checkout the grunt-json plugin to learn more about the plugin.

JSON File

The grunt-json plugin will take the following JSON data convert it into a JavaScript Object like in the next example.

{
    "name": "Product",
    "properties": {
        "id": {
            "type": "number",
            "description": "Product identifier",
            "required": true
        },
        "name": {
            "description": "Name of the product",
            "type": "string",
            "required": true
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "required": true
        },
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    }
}

JSON Converted to JavaScript

Below is what the JavaScript file will look like.

var JSON_DATA = JSON_DATA || {};
JSON_DATA["products"] = {
    "name": "Product",
    "properties": {
        "id": {
            "type": "number",
            "description": "Product identifier",
            "required": true
        },
        "name": {
            "description": "Name of the product",
            "type": "string",
            "required": true
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "required": true
        },
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    }
};

Now we can used the data like any other JavaScript Object.

console.log( JSON_DATA.products );

Leave me a comment, I love comments.

Leave a Reply