-1

I have a json object with three level of nesting I have to Iterate it Dynamically

Here is my code

var responseObj ={ 
           db_config:{
             db_user: 'das1234',
            },
           env_con:{
             db_con:'ds67'
           },
           db_password: 'ds345ty76',
           db_host: 'wdsa12'
          }    


        function decrypt(responseObj,key){  
            var list = []
            //get the keys from the responseObj 
            Object.keys(responseObj).forEach(function(key){
                    //Push the keys into a list
                    list.push(key);
                })
            console.log(list)

            try{
                for(var i =0;i<list.length;i++){
                    //Decrypt the values of the key
                    var decipher = crypto.createDecipher('aes256', key);
                    //Assign The decrypted value to the keys
                    responseObj[list[i]] = decipher.update(responseObj[list[i]], 'hex', 'utf8') + decipher.final('utf8')
                }
                return responseObj;

            }catch(err){
                console.log(err);
            }   
        }  


    var res = decrypt(responseObj,key)
    console.log(res)

had tried lot ways I just confused How to get the keys and values as iterated dynamically without using the key as static. Have any Idea about pls help to find it out.

Ramyachinna
  • 413
  • 1
  • 8
  • 20
  • *"How Do I iterate through nested properties of Json in nodejs?"* You don't. JSON is a *textual notation* for data exchange.(http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. [(More.)] You can loop through the nested properties of the object tree you get when you *parse* it, though, at which point you're not dealing with JSON anymore. But there's no JSON at all in the question, so no need for parsing. – T.J. Crowder Mar 16 '17 at 06:55
  • You're already getting the keys and using them to look up properties on the object. Where are you stuck? You seem to have the basics working above. – T.J. Crowder Mar 16 '17 at 06:57
  • Crowder you are right when trying to get the solution for json in this form I Can Here Is the Json let responseObj = { db_user: 'das1234', db_con:'ds67', db_password: 'ds345ty76', db_host: 'wdsa12', } But If Json is nested How I can proceed further? – Ramyachinna Mar 16 '17 at 07:38
  • 1
    Again: That's not JSON. That's just a JavaScript object initializer. – T.J. Crowder Mar 16 '17 at 07:41

2 Answers2

2

You already have nearly all the pieces. You know how to get the property names (keys) from an object:

Object.keys(obj);

...and how to loop through them

.forEach(...)

The only missing piece is recursion and detecting that a property's value is another object. You can test taht by using typeof: typeof something === "object" tells us that something is an object (or null).

See comments:

var responseObj = {
    db_config: {
        db_user: 'das1234',
    },
    env_con: {
        db_con: 'ds67'
    },
    db_password: 'ds345ty76',
    db_host: 'wdsa12'
};

function decrypt(obj, key) {
    // Loop through this object's properties
    Object.keys(obj).forEach(function(key) {
        // Get this property's value
        var value = obj[key];
        // If not falsy (null, empty string, etc.)...
        if (value) {
            // What is it?
            switch (typeof value) {
                case "object":
                    // It's an object, recurse
                    decrypt(value, key);
                    break;
                case "string":
                    // It's a string, decrypt
                    var decipher = crypto.createDecipher('aes256', key);
                    obj[key] = decipher.update(value, 'hex', 'utf8') + decipher.final('utf8');
                    break;
            }
        }
    })
}

var res = decrypt(responseObj, key);
console.log(res);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Lets clarify first what JSON actually is. JSON is a textual, language-indepedent data-exchange format, much like XML, CSV or YAML.

Source: What is the difference between JSON and Object Literal Notation?

That beeing said your question is about iterating the Object itself without calling for the keys. You are looking for this:

for (variable in object) {... }

Here is an example from MDN:

let obj = {a:1, b:2, c:3};

for (let prop in obj) {
  console.log("o." + prop + " = " + obj[prop]);
}

Source: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/for...in


Sidenote

I don't know what you want to achieve with your JSON structure, but you could change your JSON from this:

var responseObj ={ 
           db_config:{
             db_user: 'das1234',
            },
           env_con:{
             db_con:'ds67'
           },
           db_password: 'ds345ty76',
           db_host: 'wdsa12'
          }   

To this:

let responseObj = { 
           db_user: 'das1234',
           db_con:'ds67',
           db_password: 'ds345ty76',
           db_host: 'wdsa12',
           }

The new JSON would be flat and you don't have to worry about iterating through a nested object.

Example:

for (let prop in responseObj ) {
  console.log("o." + prop + " = " + responseObj [prop]);
}
Community
  • 1
  • 1
Megajin
  • 2,648
  • 2
  • 25
  • 44
  • ,Thanks But I have to iterate the Json which I have mentioned because I got response in this form only.I tried to use this to iterate for decrypting the json value. – Ramyachinna Mar 16 '17 at 07:33
  • You could do another inside check within the loop like : `if ( typeof responseObj [prop] === 'object'` (be careful with typeof). Then do another `for (variable in object) {... }` (recursively). After that just return your desired values. Another option would be to flatten your given JSON before you iterate it. There are serveral options here on SO. – Megajin Mar 16 '17 at 13:23