0

Considering this result I get from an ajax call:

 [
    {
        "field1": "2381",
        "field2": "1233",
        "field3": "43.79489333333333",
        "field4": "11.22697833333333"
    },
    {
        "field1": "2381",
        "field2": "1774",
        "field3": "45.70752833333334",
        "field4": "9.489278333333333"
    }
]

and having an ajax call it keeps returning "unexpected character" error and I have this kind of call I use:

jQuery.ajax({ 
    type: "GET",
    dataType: "json",
    url: "/myUrl.php",
    success: function(data) {
        console.log(data);
        var arrayObjects = JSON.parse(data);
    }
}); 

So since I read on the internet this kind of ajax calls, it says:

[{"value": "test"}] is valid 

So I wonder why my object keeps returning "unexpected character".

Luigino
  • 745
  • 3
  • 7
  • 26
  • 1
    *Where* does your code return "unexpected character"? What is the output of `console.log(data)`? –  Nov 26 '13 at 13:25
  • this is the output of console.log(data): [Object { field1="2381", field2="1233", field3="43.79489333333333", more...}, Object { field1="2381", field2="1774", field3="45.70752833333334", more...}] – Luigino Nov 26 '13 at 13:27
  • it's already in the JSON format, not a string – Moho Nov 26 '13 at 13:30
  • 1
    @Moho, "it's already in the JSON format, not a string" Perhaps you meant "it's already an object, not a JSON string"? JSON is always a string, when you are using the JSON syntax in your code to create native objects it's simply an object literal, not JSON. – plalx Nov 26 '13 at 13:39

3 Answers3

3

When using jQuery.ajax, if you specify the dataFormat, it will try to automatically parse the response according to the specified format before passing the data to the callback function.

Therefore, what you receive in your callback is not a JSON string, it's a JavaScript object already, which doesn't require any parsing.

jQuery.ajax({ 
    type: "GET",
    dataType: "json", // <-- this specifies the data format already
    url: "/myUrl.php",
    success: function(data) {
        console.log(data[0]); //logging first record
        //var arrayObjects = JSON.parse(data); //not needed

    }
}); 
plalx
  • 42,889
  • 6
  • 74
  • 90
0

It seems the data returned from the API is already an array.

You're trying to parse an array, so the error.

so change

var arrayObjects = data;
Praveen
  • 55,303
  • 33
  • 133
  • 164
0

By setting dataType: "json" you are telling jQuery to parse the received data as JSON, so data is delivered to the success() function as a Javascript array.

See: http://api.jquery.com/jQuery.ajax/

Claudi
  • 5,224
  • 17
  • 30