所以,我有这个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文件,其中嵌套可能不同。
答案 0 :(得分: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'));
答案 1 :(得分: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(',',''));