Reputation: 922
how can i create a folder structure using this json structure
{
"europe": {
"poland":{},
"france":{},
"spain":{},
"greece":{},
"UK":{},
"germany":"txt"
},
"Asia": {
"india":"xml"
},
"Africa":null
}
in such a way that
anyone know how to do this in nodejs?
Upvotes: 3
Views: 6669
Reputation: 31
Update
I was also looking for a solution to create files and folders based on a JSON and found this interesting node module "node-jsondir"
Here is an example of how it works:
var jsondir = require('jsondir');
jsondir.json2dir({
"-path": 'path/to/directory',
"myfile": {
"-content": 'Hello world!'
},
"mydir": {
"a": {
"b": {
"c": {
"-type": 'd'
}
}
},
"1": {
"2": {
"3": {}
}
}
}
}, function(err) {
if (err) throw err;
});
Tested and it works.
Node module is https://www.npmjs.com/package/jsondir
Upvotes: 0
Reputation: 318322
You'll have to recursively iterate and create folders and files.
Not tested, but something like this should be close
var fs = require('fs');
var obj = {
"europe": {
"poland": {},
"france": {},
"spain": {},
"greece": {},
"UK": {},
"germany": "txt"
},
"Asia": {
"india": "xml"
},
"Africa": null
};
(function create(folder, o) {
for (var key in o) {
if ( typeof o[key] === 'object' && o[key] !== null) {
fs.mkdir(folder + key, function() {
if (Object.keys(o[key]).length) {
create(folder + key + '/', o[key]);
}
});
} else {
fs.writeFile(folder + key + (o[key] === null ? '' : '.' + o[key]));
}
}
})('/', obj);
Upvotes: 3