簡體   English   中英

如何遍歷nodejs中Json的嵌套屬性?

[英]How Do I iterate through nested properties of Json in nodejs?

我有一個具有三層嵌套的json對象,我必須對其進行動態迭代

這是我的代碼

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)

我嘗試了很多方法,我只是感到困惑,如何動態地獲取鍵和值,而又不使用靜態的鍵。 有任何關於請幫助的想法可以找到答案。

您已經掌握了幾乎所有內容。 您知道如何從對象獲取屬性名稱(鍵):

Object.keys(obj);

...以及如何遍歷它們

.forEach(...)

唯一缺少的部分是遞歸並檢測到屬性的值是另一個對象。 您可以使用typeof來測試taht: typeof something === "object"告訴我們something是一個對象(或null )。

看評論:

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);

首先讓我們澄清一下什么是JSON。 JSON是一種文本形式的,不依賴語言的數據交換格式,非常類似於XML,CSV或YAML。

來源: JSON和對象文字表示法有什么區別?

那只蜜蜂說你的問題是關於迭代對象本身而不需要鍵。 您正在尋找這個:

for (variable in object) {... }

這是來自MDN的示例:

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

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

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


邊注

我不知道您想使用JSON結構實現什么,但是您可以從中更改JSON:

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

對此:

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

新的JSON將是扁平的,您不必擔心通過嵌套對象進行迭代。

例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM