How to get around or make PHP json_decode not alter my very large integer values?

瘦欲@ 提交于 2019-11-27 15:44:00

To quality JSON spec use:

// wrap numbers
$json = preg_replace('/:\s*(\-?\d+(\.\d+)?([e|E][\-|\+]\d+)?)/', ': "$1"', $json);
// as object
$object = json_decode($json);
// as array
$array = json_decode($json, true);
Ryan

Thanks @Scott Gottreu and @pospi.

The answer was in the last comment for the accepted answer on this question.

Use the preg_replace() function to surround all integer values with quotes.

json_decode(preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $jsonString), true);

Actually after testing the above line it screws up JSON with floating point numbers in as values so to fix that issue I used the following to just enclose all numbers (integer or floating point numbers) in quotes:

json_decode(preg_replace('/("\w+"):(\d+(\.\d+)?)/', '\\1:"\\2"', $jsonString), true);

Meanwhile, PHP has fixed this problem ... well, somehow. Starting sometime around PHP 5.4 they added an option which does the just what the Regex solutions posted above do:

json_decode($json, false, 512, JSON_BIGINT_AS_STRING);

The 512 refers to the default maximum nesting depth.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!