So, i have this json file, in which i have to take out the fileName tag, and use it.
{
"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"
}
}
},
im using d3.js mostly, but some parts of jquery and javascript with it. right now im doing:
d3.json(url,function(json){
var jsondata=json;
var temp = jsondata.dataset.fileDscr.fileTxt.fileName;
}
Is there a way to just access fileName directly? Im asking because, i have to make this generic to fit other json files, where the nesting might be different.
This will return the value for some instance of the key in the JSON data, if it exists.
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'));
It will return a comma separated string of all the values of a specified key
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(',',''));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.