Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with encoding Json request

I try to manually build a Json string to send to the client.

{'result':'hhh'} 

When I use

echo json_encode(array('result'=>'hhh'));

It arrives perfectly. But when I do

echo "{'result':'hhh'}";

It isn't

The only difference I find between the two requests is that the first one has:

Content-Length: 9    header

and the second one (which does not work)

Content-Length: 16   header

Both the strings should have been content length: 16!!! I guess it something to do with the combination of ZF and Mootools.

like image 443
Itay Moav -Malimovka Avatar asked Jun 21 '26 15:06

Itay Moav -Malimovka


2 Answers

According to the specs, JSON requires double quotes around key names and string values.

echo json_encode(array('result'=>'hhh'));

will output

{"result":"hhh"}

The length of this output is 16 bytes as shown by the following:

echo strlen(json_encode(array('result'=>'hhh')));

outputs "16".

Any JSON decoder that follows the specs will fail or throw an exception when presented with your manually echoed JSON.

like image 97
Elmo Avatar answered Jun 24 '26 08:06

Elmo


It doesn't have problems with UTF-8 so much as UTF-8 is the standard encoding for it. It sounds as if you're echoing something in a different encoding scheme, which breaks, whereas json_encode() is transcoding it for you.

like image 21
chaos Avatar answered Jun 24 '26 07:06

chaos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!