【问题标题】:json_decode return null with different qoutejson_decode 用不同的引号返回 null
【发布时间】:2016-01-14 14:50:03
【问题描述】:

json_decode('["foo","bar"]', true),这可行,但返回NULL,json_decode("['foo','bar']", true)。 json_last_error() 输出 4、JSON_ERROR_SYNTAX。

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

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"]' 作为解决方法?

【问题讨论】:

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

标签: php json


【解决方案1】:

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

另见ECMA-404,它定义了 JSON 格式:

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

如果您正在寻找将您的 JSON-ish 字符串(它来自哪里?最好修复无效 JSON 的来源)转换为有效 JSON 的东西; str_replace('\'', '"', $jsonInput) 应该适用于简单的情况。


1(U+0022 是双引号 ")

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 2019-04-27
      • 2012-11-14
      相关资源
      最近更新 更多