简体   繁体   中英

$.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",
  }
]

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"
  }
]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM