Flatten a folder to a JSON file representing its contents
Often, your project will depend on data in static files - configs, language files, templates, CSV data, and so on. Loading each of these files separately is a nuisance, and results in unnecessary HTTP requests.
This task combines all those files into a single .json file. For example if you had a folder that looked like this...
data|- config.json|- tables|- population.csv|- growth.csv|- slides|- 0.txt|- 1.txt|- 2.txt|- 3.txt|- i18n|- en-GB.json|- en-US.json|- fr.json|- de.json
...you would get JSON that looked something like this, except minified:
"config":// contents of config.json"tables":"population": // contents of population.csv"growth": // contents of growth.csv"slides":"contents of 0.txt""contents of 1.txt""contents of 2.txt""contents of 3.txt""i18n":"en-GB":// contents of en-GB.json"en-US":// contents of en-US.json"fr":// contents of fr.json"de":// contents of de.json
If a file contains JSON, it is stored as JSON; if not, it is stored as text. If a folder only contains items with numeric filenames (as in the case of the
slides folder above), it will become an array rather than an object.
This plugin requires Grunt
If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:
npm install grunt-dir2json --save-dev
In your project's Gruntfile, add a section named
dir2json to the data object passed into
A pattern, or array of patterns, of filenames to exclude, e.g.
**/*/notes.md. Uses the standard globbing syntax.
Thumbs.db files will always be excluded - you don't need to specify these.
Function ( content, srcpath )
A function to process content. Will be applied to all files - if you want to selectively apply, filter by
Transforms values and properties when stringifying JSON. See the MDN docs
Pretty-prints the result using this string. See the MDN docs
If supplied, dir2json will create JSONP instead of JSON (note that the destination filename should end
.js and not
.json in this case)
true, dir2json will create an AMD module (as above, extension should be
This will read the contents of
project/data and write a JSON file representing its contents to
In this (slightly contrived) example, there are two targets -
dist. In both cases .md files will be excluded, and .csv files will be parsed using an imaginary
csv-to-json module. In the
dist target, any files named
debug_hints.json will also be excluded.
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.