LoginSignup
3
4

More than 5 years have passed since last update.

Gruntで複数のJSONファイルを結合する

Last updated at Posted at 2016-01-15

JSONファイルが長くなると管理が難しくなるので、個別のJSONファイルを更新して
Gruntで結合することにした。

結合前

file
project
 ├ app
 ├ json-src
  ├ book-1.json
  ├ book-2.json
  └ option.json

book-1.json

json
{
  "title": "Title-1",
  "auther": "auther1",
  "description": "Title-1 description"
}

book-2.json

json
{
  "title": "Title-2",
  "auther": "auther2",
  "description": "Title-2 description"
}

option.json

json
{
  option:{
    info1: "...",  
    info2: "..."  
  }
}

結合後のイメージ

file
project
 ├ app
 ├ book-all.json ← コレ!
 ├ json-src
  ├ book-1.json
  ├ book-2.json
  └ option.json

book-all.json

json
{
  book:[
    {
      "title": "Title-1",
      "auther": "auther1",
      "description": "Title-1 description"
    },
    {
      "title": "Title-2",
      "auther": "auther2",
      "description": "Title-2 description"
    }
  ],
  option:{
    info1: "...",  
    info2: "..."  
  }
}

grunt.js

var fs = require('fs');

grunt.task.registerTask( 'build-json' , '' , function(){

    console.log('\n\n\n- - - - JSON連結開始 - - - - -\n\n');

    // 結合用データ
    var resultObj = {
        book:[],
        option:{}
    };

    // 対象フォルダ「./app/json-src/」
    grunt.file.recurse('./app/json-src/', process );

    // 対象フォルダに対し、再帰的処理
    function process(abspath, rootdir, subdir, filename){

        // 処理対象はJSONファイルに限定
        // option.jsonは別処理したいのでここで除外
        if( filename.indexOf('book') > -1 && filename.indexOf('.json') > -1 ){
            // JSONの読み込み
            var bookObj = JSON.parse(fs.readFileSync( abspath , 'utf8'));
            resultObj.book.push( bookObj );
        }

    }

    // 残りのoption.jsonを統合
    var optionObj = JSON.parse(fs.readFileSync( './app/json-src/option.json' , 'utf8'));
    resultObj.option = resultObj;

    console.log('結果検証:', resultObj );

    // String化してファイルに書き込む
    // stringifyの第2,3引数をこういうふうに書くと整形されたJSONにしてくれる。すばらしい。
    grunt.file.write( './app/book-all.json' , JSON.stringify(resultObj,null,'    ') );

});

実行
grunt build-js

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4