0

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",
  }
]
2
  • your JSON file is not valid :) Commented Dec 23, 2015 at 12:15
  • jsonlint.com is useful. Commented Dec 23, 2015 at 12:18

2 Answers 2

4

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

Comments

0

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

Comments

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.