0

I am trying to parse a JSON file that has this code:

{
    "employees": [
        { "firstName":"John" , "lastName":"Doe" }, 
        { "firstName":"Anna" , "lastName":"Smith" }, 
        { "firstName":"Peter" , "lastName":"Jones" }
    ]
}

with this small script:

<script>
    var obj = $.parseJSON("employe.json")
</script>

I just want to use the employees object, but I am getting this error:

SyntaxError: JSON.parse: unexpected character @ http://code.jquery.com/jquery-1.9.1.min.js:3

I also tried the same thing with getJSON, but it did not work either.

Is getJSON for external files and parseJSON for json string?

13
  • parseJSON parses json strings into objects. getJSON uses parseJSON internally, so it does the parsing automagically. When you get the "unexpected character" error, it's almost always because the JSON is invalid, and there are characters that should'nt be there. Commented Apr 9, 2013 at 23:48
  • I copied and pasted my JSON file, do you see any error? Commented Apr 9, 2013 at 23:52
  • You can test your json at : jsonlint.com, also the error console should tell you what character is causing the problem. Commented Apr 9, 2013 at 23:55
  • You should always read the documentation. I guess if you had looked at api.jquery.com/jQuery.parseJSON, you would have seen that it accepts a JSON string, not a URL. api.jquery.com/jQuery.getJSON also provides some examples, maybe they are helpful? Commented Apr 9, 2013 at 23:58
  • Read what I said, I was already assuming parseJSON was taking a string. The reason I was using parseJSON, was becuse getJSON wasn't working. But thanks for the help! Commented Apr 10, 2013 at 0:01

1 Answer 1

3

You should be loading the json file first, then sending the resulting string contents of that document into the parse statement.

$.ajax({url: "employe.json"}).done(function(data){
    console.log($.parseJSON(data));
});
Sign up to request clarification or add additional context in comments.

5 Comments

I see, I need to load the JSON file first. I still get a similar error: "malformed". And it points to the first bracket of my JSON file.
Oh right. But I just found out that getJSON is a shortcut to that.
Just did and all my JSON is valid :S
Log out data before you parse it, make sure it's loading the data. Maybe also try using JSON.parse instead (remove a layer.)
@Maxwell did you get this sorted?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.