Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid PHP JSON encoding

I'm working on a project in PHP (5.3.1) where I need to send a JSON string to a webservice (in python), but the result I get from json_encode does not pass as a valid JSON (i'm using JSLint to check validity).

I should add that the structure I'm trying to encode is fairly big (13K encoded), and consists partially of UTF8 data, and while json_encode does handle it, i get spaces in weird places in the result. For example, I could get {"hello":tru e} or {"hell o":true} which results in an error from the webservice since the JSON is invalid (or data, like in the second example).

I've also tried to use Zend framework for JSON encoding, but that didn't make much different.

Is there a known issue with JSON in PHP? Did anyone encounter that behavior and found a solution?

like image 808
Ofir Avatar asked Nov 24 '09 14:11

Ofir


2 Answers

You state that "the structure I'm trying to encode ... consists partially of UTF8 data." This implies that it is also partially of non-UTF8 data. The json_encode doc has a comment at the bottom, that

json_encode() expects strings to be encoded to be in UTF8 format, while by default PHP strings are ISO-8859-1 encoded. This means that

json_encode(array('àü'));

will produce a json representation of an empty string, while

json_encode(array(utf8_encode('àü')));

will work.

Are the failing segments of the JSON due to non-UTF8 input?

like image 62
Ewan Todd Avatar answered Sep 27 '22 22:09

Ewan Todd


For sure object keys cannot contain spaces or any non unicode characters, unquoted variables can be only boolean, integer ,float, object and array value, strings should always be quoted.

Also, I would recommend you to add correct header before your json output.

if(!headers_sent())
   header('Content-Type: application/json; charset=utf-8', true,200);

Can you also post your array or object that you passing to json_encode?

like image 38
Nazariy Avatar answered Sep 27 '22 23:09

Nazariy