2016-01-14 91 views
0

json_decode('["foo","bar"]', true),这个工程,但这个返回NULL,json_decode("['foo','bar']", true)json_last_error()输出4,JSON_ERROR_SYNTAXjson_decode返回null与不同的qoute

我检查了以下问题的一些答案;

json_decode() returns null issues

PHP json_decode() returns NULL with valid JSON?

json_decode returns NULL after webservice call

,并试图以下解决方案,但没有成功;

json_decode(str_replace('"', '"', "['foo','bar']"), true)

json_decode(stripslashes(str_replace('\"', '"', "['foo','bar']")), true)

json_decode(stripslashes("['foo','bar']"), true)

json_decode(utf8_encode("['foo','bar']"), true)

我不认为它与UTF-8 BOM做。它是一个PHP的错误?或者我该如何将"['foo','bar']"转换为'["foo","bar"]'作为解决方法?

+1

的字符串的功能'json_decode'作为一个参数需要是有效的JSON。 '{“a”:1,“b”:2,“c”:3,“d”:4,“e”:5}'这是有效的JSON。你只是传入一个用引号括起来的数组。 – sidneydobber

回答

0

JSON字符串用双引号引用"。单引号'(这在PHP中很常见)不是有效的JSON。没有讨论。因此,输入['foo','bar']是无效的JSON和json_decode正确地拒绝解析它

另请参阅ECMA-404,它定义了JSON格式:

字符串是的包裹引号(U + 0022)Unicode代码点的序列。

如果你正在寻找的东西到你的JSON上下的字符串(它从何从修复无效JSON的来源,最好是?)转换为有效的JSON; str_replace('\'', '"', $jsonInput)应该在简单情况下工作。


U+0022是双引号"

0

你没有提供有效的json函数。如果你使用javascript数组

 ["foo","bar"]
你应该使用JSON.stringify在js端实际上生成JSON。