Syed
Syed

Reputation: 16513

GULP: Get all SVGs in JSON

I have many SVG icons that needs to be served through JSON. I like to have a task that get all the SVG do something like this.

{
  "name": "icon-file-name",
  "data": "<svg version=\"1.1\">...</svg>"
},
{
  "name": "icon-file-name",
  "data": "<svg version=\"1.1\">...</svg>"
}

So far I have just this:

gulp.task('buildSvgIcon', function() {
  return gulp.src([ paths.svgIcons + '*.svg'])
    .pipe(gulp.dest('./www/assets/cleaned-up-svg-icons/'));
});

Here is what I need:

  1. Get the file name and add it to "name".
  2. Get the SVG data and add it to "data".
  3. Add backslash for double quote. for eg. version=\"1.1\".

If you can just tell me an Idea how this can be done that would be great help.

Upvotes: 0

Views: 308

Answers (1)

Igor Semin
Igor Semin

Reputation: 2496

Something like this:

var fc2json = require('gulp-file-contents-to-json');
var jsonTransform = require('gulp-json-transform');

gulp.task('svg', function() {

    gulp.src(config.paths.svg)
        .pipe(fc2json('contents.json'))
        .pipe(jsonTransform(function(data) {

            var resultJson = '',
                objects = [],
                keys = Object.keys(data);

            for (var i = 0; i < keys.length; i++) {

                objects.push({
                    name: keys[i],
                    data: data[keys[i]]
                });
            }

            // return objects; it's correct json

            var i = 0;
            objects.map(function(e) {

                i++;
                resultJson += JSON.stringify(e) +
                    (i == keys.length ? '' : ',\n');
            });

            return resultJson; // it's just what you want in result file, but it's no valid json file
        }))
        .pipe(gulp.dest(config.paths.dist + '/svg_json'));
});

Upvotes: 1

Related Questions