Reputation: 21
I've spent the last few days trying to get around this problem. Every time I try to get a JSON object using Angular's $http.get, I get "Error: JSON.parse: unexpected character".
My JSON is created using the PHP's json_encode. The PHP code is the following:
header('Content-Type:application/json');
echo json_encode($to_encode);
The JSON it creates looks like this:
{"id":"1","para":{"para_id":"1","story_id":"1","para_content":""\u017bagiel na horyzoncie!" - s\u0142ycha\u0107 krzyk z bocianiego gniazda. Fregata Jego Kr\u00f3lewskiej Mo\u015bci "Acanta" \u017cwawo sunie przez b\u0142\u0119kit oceanu. Ty, jej dow\u00f3dca, stoisz na rufie. Bosman i sternik patrz\u0105 si\u0119 na ciebie, oczekuj\u0105c rozkaz\u00f3w."},"tunnels":[{"tunnel_id":"1","start_para_id":"1","end_para_id":"2","tunnel_content":"Spokojnie, zbli\u017cmy si\u0119 i sprawd\u017amy, kto to."},{"tunnel_id":"2","start_para_id":"1","end_para_id":"3","tunnel_content":"Bi\u0107 na alarm! Za\u0142oga do dzia\u0142!"}]}
(It's UTF8-encoded Polish, if it's relevant; the text is just a placeholder)
The JS that gets it look like this:
$scope.current_para = $http.get("/gamebook/run");
$scope.current_para.then(function(os){result = os.data; console.log(result);}
Instead of a neat JSON in my console.log, I get the error, even though my Firebug tells me that the GET method was successful and even shows me the JSON it received.
Upvotes: 1
Views: 1473
Reputation: 21
I've finally found a workaround to this problems - I still don't know what or why happened, but here's what could be done.
On the server side you have to wrap your JSON data in single quotes (making it a string) then use eval() in JS to turn it back into JSON.
I know it's not elegant, but that's the only solution I've found. Hope it'll help someone.
Thanks everyone for the input!
Upvotes: 1