Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grunt - read json object from file

Tags:

json

gruntjs

I want to use grunt-hash plugin for renaming my js files. This plugin create a new file containing map of renamed files:

hash: {
    options: {
        mapping: 'examples/assets.json', //mapping file so your server can serve the right files

Now I need to fix links to this files by replacing all usages (rename 'index.js' to 'index-{hash}.js') so I want to use grunt-text-replace plugin. According to documentation I need to cofigure replacements:

replace: {
  example: {
     replacements: [{
       from: 'Red', // string replacement
       to: 'Blue'
     }]
   }
}

How could I read json mapping file to get {hash} values for each file and provide them to replace task?

like image 911
Livon Avatar asked Jul 24 '14 12:07

Livon


1 Answers

grunt.file.readJSON('your-file.json')

is probably what you are looking for.

I've set up a little test. I have a simple JSON file 'mapping.json', which contains the following JSON object:

{
  "mapping": [
    {"file": "foo.txt"},
    {"file": "bar.txt"}
  ]
}

In my Gruntfile.js I've written the following simple test task, which reads the first object in the 'mapping'-array:

grunt.registerTask('doStuff', 'do some stuff.', function() {
  mapping = grunt.file.readJSON('mapping.json');
  grunt.log.write(mapping.mapping[0]["file"]).ok();
});

When invoking the Grunt task, the console output will be as follows:

$ grunt doStuff
Running "doStuff" task
foo.txtOK

Done, without errors.

I hope this helps! :)

like image 89
lukasender Avatar answered Nov 06 '22 06:11

lukasender