Reputation: 93
I have a php class( ajax called) which returns json_encode
data as
["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]
I'm trying to do jquery.parseJSON(data)
and it's giving me error "Unexpected number"
, what am I doing wrong?
Upvotes: 0
Views: 107
Reputation: 92294
You are trying to parse an array, not a string. JSON.parse
(and any other JSON parser) expects a string, therefore Array.toString
is called and your call becomes jquery.parseJSON("2016-02-08 09:00:00.000,2016-02-15 09:00:00.000")
//Error "Unexpected number", toString is called on the input array
JSON.parse(["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"])
// Returns an array object
JSON.parse('["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]') // OK
If you are using the return of json_encode
inline, you don't need to parse it, just assign it to a variable, JavaScript will do the parsing.
var dates = <?= json_encode($dates) ?>;
If you are using jQuery
the data will typically already be parsed into JSON in the callback, if it doesn't, you can force it using dataType: 'json'
Upvotes: 2
Reputation: 350750
jQuery does the decoding for you when you perform the AJAX call with the JSON dataType:
$.ajax({
url: 'mypage.php',
data: mydata,
dataType: 'json'
})
.done(function(response) {
// Response is an array, not a JSON string, jQuery decoded it.
// Demo:
console.log(response[0]); // "2016-02-08 09:00:00.000"
console.log(response[1]); // "2016-02-15 09:00:00.000"
}
This is explained in the jQuery docs:
dataType
...
"json"
: Evaluates the response as JSON and returns a JavaScript object.
So, don't use jquery.parseJSON
on the result. It has already been done for you.
Upvotes: 0
Reputation: 673
var x = '["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]';
$.parseJSON(x) // return an array
Upvotes: 0