Ghozt
Ghozt

Reputation: 267

json variable is undefined

I have a json file in a folder called json/img_desc.json

Here is the json file

{ "theimages":[
  {
    "number":1,
    "title":"Joy Toy teddy bear",
    "description":"In etc etc"
  } etc etc

Then I used this code to try and get the first value.

 $.getJSON('json/img_desc.json', function(theimages) {
    console.log(img_desc.theimages.number[0]);
});

The error

It says this

[15:06:46.951] ReferenceError: img_desc is not defined @ file:///[removed for privacy]/js/puzzle.js:246

Upvotes: 0

Views: 133

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76508

 $.getJSON('json/img_desc.json', function(img_desc) {
    console.log(img_desc.theimages.number[0]);
});

Should fix your problem. As if you have any other problem, ask it in a separate question.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

it should be

$.getJSON('json/img_desc.json', function (theimages) {
    console.log(theimages.theimages[0].number);

    //if you want to loop
    $.each(theimages.theimages, function (idx, obj) {
        console.log(obj.number)
    })
});

Upvotes: 5

thefourtheye
thefourtheye

Reputation: 239473

Documentation says http://api.jquery.com/jQuery.getJSON/#jQuery-getJSON-url-data-success-data--textStatus--jqXHR- it will pass a plain object as the second parameter. So, you can do something like this

$.getJSON('json/img_desc.json', function(theimages) {
    $.each(theimages.theimages, function( index, val ) {
        console.log(val, val.number);
  });
});

Upvotes: 2

Related Questions