2016-08-17 102 views
0

所以,我有這個json文件,其中我必須取出fileName標籤,並使用它。如何使用javascript訪問json中的嵌套密鑰

{ 
"dataset": { 
    "private": false, 
    "stdyDscr": { 
     "citation": { 
      "titlStmt": { 
       "titl": "Smoke test", 
       "IDNo": { 
        "text": "10.5072/FK2/WNCZ16", 
        ".attrs": { 
         "agency": "doi" 
        } 
       } 
      }, 
      "rspStmt": { 
       "AuthEnty": "Dataverse, Admin" 
      }, 
      "biblCit": "Dataverse, Admin, 2015, \"Smoke test\", http://dx.doi.org/10.5072/FK2/WNCZ16, Root Dataverse, V1 [UNF:6:iuFERYJSwTaovVDvwBwsxQ==]" 
     } 
    }, 
    "fileDscr": { 
     "fileTxt": { 
      "fileName": "fearonLaitinData.tab", 
      "dimensns": { 
       "caseQnty": "6610", 
       "varQnty": "69" 
      }, 
      "fileType": "text/tab-separated-values" 
     }, 
     "notes": { 
      "text": "UNF:6:K5wLrMhjKoNX7znhVpU8lg==", 
      ".attrs": { 
       "level": "file", 
       "type": "VDC:UNF", 
       "subject": "Universal Numeric Fingerprint" 
      } 
     }, 
     ".attrs": { 
      "ID": "f6" 
     } 
    } 
}, 

即時使用d3.js主要是,但一些部分的jQuery和JavaScript與它。現在我在做:

d3.json(url,function(json){ 

       var jsondata=json; 

        var temp = jsondata.dataset.fileDscr.fileTxt.fileName; 
} 

有沒有辦法直接訪問fileName?我問,因爲,我必須使這個通用適合其他json文件,其中嵌套可能會不同。

+0

你所說的「直接」的意思是一個逗號分隔字符串指定鍵? –

+0

你的意思是你想要一種搜索​​未知對象結構的方法來獲取與「'fileName」''等已知密鑰名稱相關聯的值嗎?如果密鑰在對象中出現多次(如在你的例子中的「.attrs」')? (請注意,回調中的'json'參數和jsondata'變量實際上都不包含JSON,它們都是通過解析JSON而創建的對象的引用。) – nnnnnn

+0

[Access/process(nested)objects,數組或JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Naga2Raja

回答

1

這將返回JSON數據中某個鍵的實例的值(如果存在)。

var data = {...}; 
function findValue(json, key) { 
    if (key in json) return json[key]; 
    else { 
    var otherValue; 
    for (var otherKey in json) { 
     if (json[otherKey] && json[otherKey].constructor === Object) { 
     otherValue = findValue(json[otherKey], key); 
     if (otherValue !== undefined) return otherValue; 
     } 
    } 
    } 
} 
console.log(findValue(data, 'fileName')); 
+0

謝謝!這工作完美! :) –

0

它將返回的所有值的

function walk(obj,keyname) {  
    var propertyVal="";                     
     for (var key in obj) { 
      if (obj.hasOwnProperty(key)) { 
       var val = obj[key];                      
       if(typeof(val) == 'object') { 
        console.log(val);                        
        propertyVal+= walk(val,keyname);             
       }else { 
        if(key == keyname){              
         propertyVal = propertyVal+","+obj[key];                  
        } 
       } 
      } 
     } 
     return propertyVal;       
} 
alert(walk(data,'filename').replace(',','')); 
相關問題