1

I have the following recursive function saved in a file called helpers.js. When it is loaded into the main app.js file using:

var helpers = require('./helpers');

calling it only works partially. The line:

s+=recurseJSON(o[a]);

doesn't get called so the JSON parsing doesn't recurse into nested levels.

I have also tried the following which still doesn't work:

s+=helpers.recurseJSON(o[a]);

If I move the code below into the main app.js file, the recursion works perfectly, obviously changing

recurseJSON: function(o) {...

to

function recurseJSON(o) {..

Your thoughts are appreciated. Here is the whole code:

module.exports = {
recurseJSON: function(o){
    var s = '';
    for(var a in o){
        if (typeof o[a] == 'object'){
            s+=a+':';
            console.log('JSON>', a, ":");
            s+=recurseJSON(o[a]);  // This line should recurse but doesn't
        }else{
            s+=a+':'+o[a]+'   ';
            console.log('JSON>', a, ":", o[a]);
        }//end if
    }//end for
    return s;
}
};

PS: Credit to Recursively parsing JSON for the original recursive code.

2
  • When a function calls itself, that is recursive, not iterative. You likely iterate through each key/value pair in JSON, but in a recursive fashion. Commented Jul 1, 2017 at 6:30
  • See this answer stackoverflow.com/a/26536906 Commented Jul 1, 2017 at 6:41

1 Answer 1

1

While leaving the export statement like this:

module.exports = {
  recurseJSON: function(o){
    ...
  }
};

You can call the function recursively using the statement s+=this.recurseJSON(o[a]), but only assuming that the only way you invoke the recurseJSON() function outside the file is

helpers.recurseJSON(obj)

so that recurseJSON() is the calling member of helpers, making the this in recurseJSON() refer to helpers.

If you cannot guarantee this, then the correct way to invoke it, which is more verbose, is

s+=module.exports.recurseJSON(o[a])

Update

Another simpler solution is to just name the function you're exporting:

module.exports = {
  recurseJSON: function recurseJSON(o){
    ...
  }
};

Then you can just use s+=recurseJSON(o[a]) like you had before.

Sign up to request clarification or add additional context in comments.

1 Comment

s+=module.exports.iterateJSON(o[a]) This worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.