|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2013-01-04 01:04 UTC] sreed at ontraport dot com
Description:
------------
When you use json_encode with an invalid UTF-8 byte sequence in a string PHP will
generate a warning (with display_errors set to off) and the function returns an
invalid json encoded string. The string with the invalid UTF-8 byte sequence is
replaced with null (for example: {null:""}). This is invalid json and can not be
decoded with json_decode.
I would think the expected behavior should be that json_encode should never
returns an invalid json encoded string. It should either return false on failure
as the documentation states or the invalid UTF-8 byte sequence should be handled
in a way that does not corrupt the json string.
Test script:
---------------
$key = "Foo " . chr(163);
$array = array($key => "");
var_dump($array);
$json = json_encode($array);
echo $json."\n";
var_dump(json_decode($json));
Expected result:
----------------
I would expect the returned json string to be valid or for json_encode to return
false.
Actual result:
--------------
array(1) {
["Foo �"]=>
string(0) ""
}
{null:""}
NULL
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Oct 24 01:00:02 2025 UTC |
I tried the code in git/svn HEAD right now (last commit aafce7353e "merge branch 5.6") so I assume whichever code discussed here is included (no patch on this report). I added a test with a string with a tab and it does not return false. I think it should remove inescapable chars (and maybe issue a log warning) and for chars with a escape sequence, it should just encode it. --TEST-- json_decode() tests --SKIPIF-- <?php if (!extension_loaded("json")) print "skip"; ?> --FILE-- <?php var_dump(json_encode('a'.chr(9).'b')); // char with usable escape sequence (tab) var_dump(json_encode('a'.chr(1).'b')); // char with no usable escape sequecne ?> --EXPECTREGEX-- string\(4\) \"a\tb\" string\(2\) \"ab\"