Reputation: 83
I would like to merge my json files with a gulp task with a prefix per jsonfile.
I have several json files like this
{
"en": {
"title": "Component title english",
"subtitle": "Component subtitle english",
},
"nl": {
"title": "Component title dutch",
"subtitle": "Component subtitle dutch",
}
}
I would like to merge these with the component name as a prefix so the outcome of the merge will be come something like this:
"componentBlogBox": {
"en": {
"title": "Component title english",
"subtitle": "Component subtitle english",
},
"nl": {
"title": "Component title dutch",
"subtitle": "Component subtitle dutch",
}
}
},
"componentCaseSlider": {
"en": {
"title": "Caseslider title english",
"subtitle": "caseslider subtitle english",
},
"nl": {
"title": "Component title dutch",
"subtitle": "Component subtitle dutch",
}
}
I have this gulp task using node module gulp-merge-json but this just replaces the keys to form one.
gulp.task('json-merge', function(){
gulp.src(['dest/json/blog-box/home.json', 'dest/json/case-slider/home.json'])
.pipe(jsonMerge('combined.json'))
.pipe(gulp.dest('dest/json'));
});
Is there a way to merge using a gulptask and without editing all my json files?
Upvotes: 0
Views: 520
Reputation: 83
Awesome Sven, just what I was looking for. The camelcase thing wasn't really an must-have but it's a nice touch for further development.
I simplified it into this
gulp.task('json-merge', function(){
return gulp.src([
'dest/json/blog-box/home.json',
'dest/json/case-slider/home.json'
])
.pipe(jsonMerge({
fileName: 'combined.json',
edit: function(parsedJson, file) {
var component = path.basename(path.dirname(file.path));
var editedJson = {};
editedJson[component] = parsedJson;
return editedJson;
}
}))
.pipe(gulp.dest('dest/json'));
});
Upvotes: 0
Reputation: 30564
gulp-merge-json
offers an edit
option that allows you to modify the parsed JSON for each file before all of them are merged.
So in your case all you have to do is stick the parsed JSON for each file into a new object like {'componentBlogBox': parsedJson}
and return that. Whether the property should be componentBlogBox
or componentCaseSlider
you can determine by looking at the path of the file:
var jsonMerge = require('gulp-merge-json');
var path = require('path');
function camelCase(str) {
return str.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
}
gulp.task('json-merge', function(){
return gulp.src([
'dest/json/blog-box/home.json',
'dest/json/case-slider/home.json'
])
.pipe(jsonMerge({
fileName: 'combined.json',
edit: function(parsedJson, file) {
var component = path.basename(path.dirname(file.path));
var editedJson = {};
editedJson[camelCase('component-' + component)] = parsedJson;
return editedJson;
}
}))
.pipe(gulp.dest('dest/json'));
});
(Credit for the camelCase
function goes to this answer.)
Upvotes: 1