Reputation: 2154
In routes/api.php
I have created following route
Route::get('/config', function(){
return response()->json([
'cdn' => cdn_url(),
'slide_image_path' => '/uploads/front-slides/',
'offer_image_path' => '/uploads/offers/',
'offer_image_thumb_path' => '/uploads/offers/thumbs/'
]);
});
In browser, I am doing
$.ajax({
url : 'https://www.example.com/api/config',
success : function(response){
var data = JSON.parse(response);
console.log(data);
}
});
and getting an error "Unexpected token o in JSON at position 1";
But when I use core php's json_encode()
the json response is getting parsed successfully.
Also when I use https://jsonformatter.curiousconcept.com/ to validate JSON
It can parse JSON without any issue no matter what I use (json_encode()
or response()->json()
). But it also gives a warning about invalid JSON.
So far, I have observed that when I use json_encode()
, the response contains a header "Content Encoding: gzip".
But when I use Laravel's response()->json()
, The header Content Encoding: gzip is absent.
I have also tried setting this header manually with header('Content-Encoding: gzip')
function while using response()->json()
. But then browser gives error "net::ERR_CONTENT_DECODING_FAILED";
I think its an issue related to content encoding or character encoding.
Upvotes: 0
Views: 1477
Reputation: 14251
It doens't seem to be anything wrong in your response. The problem is when you are receiving/parsing the data.
Try to use the stringify
method:
$.ajax({
url : 'https://www.example.com/api/config',
success : function(response){
var data = JSON.parse(JSON.stringify(response));
console.log(data);
}
});
Upvotes: 1