user2647510
user2647510

Reputation: 189

output individual values from one key JSON jQuery

I'm trying to output values from an array that has one key and multiple values in a JSON file. I've managed to output the values using $.each(), but what happens is that the value is returned as an array, because it is an array! I want to output each value individually so that the output is not an array:

<img src="one-value-output" />

<img src="two-value-output" />

etc...

JSON

var dataJson = "http://www.reneinla.com/kris/scripts/print.json";

The JSON file looks like this:

{  
  "printImages":[  
      "http://reneinla.com/kris/images/print/2008-06_KZO_TEN_01.jpg",
      "...",
      "http://reneinla.com/kris/images/print/2008-06_KZO_TEN_03.jpg"
 ]
}

JAVASCRIPT

var dataJson = "http://www.reneinla.com/kris/scripts/print.json";
//var dataArr = $.parseJSON(dataJson);
  $.getJSON(dataJson, function (data) {
    $.each(data, function (k, v) {
    console.log( v );
  });
});

I'd like to be able to output each value and append it to an src attribute, but wanted to see the console.log output first.

First Question

How do you print out, console.log, all the values from the json file?

Second Question

Is this the right approach to what i'm trying to achieve? I thought I'd use a JSON file because I have 88 values that need to be appended into the DOM. I could make the JSON file into an object, in my js file, but wanted to keep it more organized and efficient. This is still fairly new, so any insight here would be appreciated. Thanks and regards!

EDIT

I was able to get my desired result using this code:

var dataJson = "http://www.reneinla.com/kris/scripts/print.json";
//var dataArr = $.parseJSON(dataJson);
  $.getJSON(dataJson, function (data) {
    $.each(data, function (k, v) {
      var i = 0;
      for (i; i < v.length; i++){
        console.log( v[i] );
      }
    });
  });

Hooray!

Upvotes: 0

Views: 374

Answers (1)

AndrewR
AndrewR

Reputation: 6748

Looking at your JSON, what you have is an object with 1 property, which is an array of strings.

Using developer tools, you should set a breakpoint inside the $.getJSON success callback function to inspect the value of data. You'll see that data is not an array, but that you should actually be going after data.printImages. Otherwise, your code looks OK to me.

Re: Your approach. It seems like a good idea to me. Some day you might change the static .json file out for a server processed file, and you probably wouldn't have to change the client side at all to do that, other than point at a different URL.

Upvotes: 1

Related Questions