javascript - Recursively Parsing JSON Asynchronously -


let's have these json files:

company.json

{   "name" : "big corp",   "employees" : [     "employees/johnd.json"   ] } 

employees/johnd.json

{   "name" : "john doe",   "gender" : "male",   "contact" : "../contacts/johnd.json" } 

contacts/johnd.json

{   "email" : "jd@example.com", } 

they relate each other, , each value ending .json pointer file, relative file in.

in node, synchronously connecting these files tree not hard task, i'm having trouble finding asynchronous pattern it. every time think i've cracked in bug-free , efficient manner, trips me again. perhaps i'm tired. o_o

i've written synchronous version of want, , works perfectly:

var path = require('path'); var fs = require('fs');  function json(jsonpath) {    var obj = json.parse( fs.readfilesync(jsonpath, 'utf8') );    recurse(obj, jsonpath);    return obj;  }  function recurse(obj, frompath) {    (var in obj) {      if (isjsonpath(obj[i]))       obj[i] = json( path.join( path.dirname(frompath), obj[i]) );      if (obj[i] != null && typeof obj[i] == 'object')       recurse(obj[i], frompath)    } }  function isjsonpath (str) {    return typeof str == 'string' && /.json$/.test(str);  }  console.log( json('company.json') ); 

the above code, in combination files , structure mentioned previously, returns correct object:

{   "name":"big corp",   "employees":[     {       "name":"john doe",       "gender":"male",       "contact":{         "email":"jd@example.com"       }     }   ] } 

how community approach turning asynchronous piece of code? example, having asynchronous calls file system using readfile instead of readfilesync, such following output same result:

json('company.json', function (err, data) {    console.log(data);  }); 

i'm not user of node, i'm not familiar can , can't compared regular javascript, here's idea try.

if json path value detected, use object.defineproperty set key on object getter. getter perform call json file , replace file's parsed contents.

this means files loaded in if needed, aka "lazy loading". in cases, should great synchronous file operations.

your resulting object this:

{   name: "big corp",   _employees: null,   employees() {     if( this._employees === null) {       this._employees = json("employees/johnd.json");     }     return this._employees;   } } 

this may need adjustment, particularly because you're defining array there instead of in separate "employee list" file, should give general idea of how lazy load.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -