Vadim
Vadim

Reputation: 3

$.getJSON can't parse array

I'm trying to get data from json(array of objects) file using $.getJSON but i found this error: "success" function can't be executed. But it is executing if json contents object What i'm doing wrong?

My code of JS and JSON below: JS:

$.getJSON('test2.json', function(data){
      console.log('getJSON callback works');
      $.each(data, function(idx, obj){
        $.each(obj, function(key, value){
          console.log(key + ": " + value);
        });
      });
    });

JSON:

[
  {
    "user_name": "Name 1",
    "user_company": "Company 1",
    "message": "Message 2",
  },
  {
    "user_name": "Name 2",
    "user_company": "Company 2",
    "message": "Message 2",
  },
  {
    "user_name": "Name 3",
    "user_company": "Company 3",
    "message": "Message 3",
  }
]

Upvotes: 0

Views: 135

Answers (2)

Shubham
Shubham

Reputation: 1793

Remove "," at the last of each object

[
  {
    "user_name": "Name 1",
    "user_company": "Company 1",
    "message": "Message 2"
  },
  {
    "user_name": "Name 2",
    "user_company": "Company 2",
    "message": "Message 2"
  },
  {
    "user_name": "Name 3",
    "user_company": "Company 3",
    "message": "Message 3"
  }
]

Upvotes: 4

Elad
Elad

Reputation: 971

try to catch error and success

$.getJSON( "test.js", { name: "John", time: "2pm" } )
  .done(function( json ) {
    console.log( "JSON Data: " + json.users[ 3 ].name );
  })
  .fail(function( jqxhr, textStatus, error ) {
    var err = textStatus + ", " + error;
    console.log( "Request Failed: " + err );
})

Upvotes: 0

Related Questions