所以,我有这个json文件,在其中我必须取出fileName标记并使用它。

{
"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文件,其中嵌套可能不同。

最佳答案

这将返回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'));

10-01 16:57
查看更多