Reputation: 4351
I have a really small jquery program that is trying to get the the value fom a key. The JSON file looks like this:
{
"Key1": [
"http://a.com",
"http: //b.com",
"http://c.net"
],
"Key2": [
"http://a.com",
"http: //b.com",
"http://c.net"
],
"Key3": [
"http://a.com",
"http: //b.com",
"http://c.net"
]
}
I am trying to get the value of one by the key. Here is my code:
$.getJSON('url_dict.json', function(json) {
$.each(json, function(key, value) {
if (key == "Key1") {
console.log(key.value);
} else {
console.log("Nope");
};
});
});
All I ever get is Nope. If I change it to key, value, they print it out fine. I only have an issue if I try to drill down by key.
Upvotes: 0
Views: 697
Reputation: 56509
You must be looping the array.
Here the point that you have to a look is
key1 //is a string
[ "http://a.com", "http: //b.com", "http://c.net"] // an array
Hence iterate the value not the key
if (key == "Key1") {
for (var i = 0; i < value.length; i++) {
console.log(value[i]);
}
} else {
console.log("Nope");
};
Here is the JSFiddle
Upvotes: 2
Reputation: 1515
key.value is actually coming out 'undefined', followed by two 'Nope's
You can get the array out of Key1 like this:
$.each(json, function(key, value) {
if (key == 'Key1') {
console.log(value); //or value[0] will give you: http://a.com
} else {
console.log("Nope");
};
});
Upvotes: 0
Reputation: 3778
Try below code. The variable value is an array, so you need to loop over it to get each item.
$.getJSON('url_dict.json', function(json) {
$.each(json, function(key, value) {
if (key == "Key1") {
$.each(value, function(k, v) {
console.log(v);
});
} else {
console.log("Nope");
};
});
});
Upvotes: 3