2017-03-16 59 views
1
{ 
    "type" : "object", 
    "properties" : { 
     "header" : { 
     "type" : "object", 
     "properties" : { 
      "outType" : { 
       "type" : "string" 
      }, 
      "id" : { 
       "type" : "string" 
      }, 
      "application" : { 
       "type" : "string" 
      }, 
      "userId" : { 
       "type" : "string" 
      }, 
     } 
     } 
    } 

在上面的代碼段中,我只想要密鑰。我通過只給我「類型」&「屬性」的對象屬性迭代變量。但我希望所有的鍵都出現在嵌套對象中。遞歸是唯一的解決方案。但是未能將邏輯應用於上面的代碼片段。 如何識別特定鍵的值又是一個對象..?只需要提取JSON模式中存在的密鑰

我試着用這個上面的函數,是否正確?

function traverse(myObj) { 
    for (x in myObj) { 
    if typeof myObj[x] == 'string' 
    then print(x); 
    else traverse(myObj[x]) 
    } 
} 
+0

'如果(對象(CURRENTITEM)=== currentItem)'會告訴你某個東西是否是一個對象 –

+0

function traverse(myObj) \t {for(x in myObj){ \t \t if typeof myObj [x] =='string' \t \t then print(x); \t \t別的 \t \t遍歷(MyObj中[X]) \t \t} \t} 我試圖像這樣與上述功能??是否正確 –

+0

@VibhavKushwaha請使用'編輯'按鈕,如果你想添加更多的細節問題。在評論中粘貼代碼是無用的,因爲它不可讀。 –

回答

0

你可以使用reviver回調JSON.parse收集當時的按鍵,當你分析你的JSON字符串:

var keys = []; 
 
var json = '{"type":"object","properties":{"header":{"type":"object","properties":{"outType":{"type":"string"},"id":{"type":"string"},"application":{"type":"string"},"userId":{"type":"string"}}}}}'; 
 
var data = JSON.parse(json, function(key, value) { 
 
    // if the key exists and if it is not in the list then add it to the array 
 
    if (key 
 
     // && typeof value === 'object' //only required if you only want the key if the value is an object 
 
     && keys.indexOf(key) === -1) { 
 
    keys.push(key); 
 
    } 
 

 
    //return the original value so that the object will be correctly created 
 
    return value; 
 
}); 
 

 
console.log(keys); 
 
console.dir(data);

+0

謝謝,你的建議幫助了我。 –