Reputation: 69
I have files.json like this
{
"apple": "apple789121.json",
"banana": "banana537332.json",
"cherry": "cherry236832.json"
}
I want to load json on javascript, like
var fruit = apple;
$.getJSON("files.json", function(data){
//if key of files.json same with fruit variable
if(data.key == fruit){
//load json based on value of key
$.getJSON(data.fruit, function(result){
console.log("success");
})
}
})
Anyone help me please, thank you.
Upvotes: 3
Views: 112
Reputation: 28522
You can check if the object i.e : apple..etc exist inside json or not .Then , use Object.values
to get value of that object and pass same to your $.getJSON.
Demo Code :
//suppose this is return..
var data = {
"apple": "apple789121.json",
"banana": "banana537332.json",
"cherry": "cherry236832.json"
}
var fruit = "banana";
/*$.getJSON("files.json", function(data) {*/
//if that key exist
if (Object.keys(data).indexOf(fruit) > -1) {
//get values..
var files = Object.values(data)[Object.keys(data).indexOf(fruit)]
console.log(files)
//pass here
/* $.getJSON(files, function(result) {
})*/
}
/*})*/
Upvotes: 5
Reputation: 981
You can use the example from https://api.jquery.com/jquery.getjson/
var fruit = "apple";
$.getJSON("files.json", function (data) {
$.each(data, function (key, val) {
if (key === fruit) {
$.getJSON(val, function (result) {
console.log("success");
});
}
});
});
Upvotes: 4