0

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.

1
  • When i try it i do not always get Nope, i get undefined and nope. Your key's don't have value properties (they're strings!). jsfiddle.net/m3gfx Commented Oct 3, 2013 at 17:37

3 Answers 3

3

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");
       };
    });
});
Sign up to request clarification or add additional context in comments.

Comments

2

You must be looping the array.

Updates:

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

Comments

0

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");
   };
});

1 Comment

Could I get this to return the array outside of the function, passs it to a var? Could I assign a global like var ulrs = value(); then return urls; ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.