json_encodejson_decode有一个奇怪的行为,我找不到解决办法:

我的php应用程序调用php web服务.Web服务返回如下所示的json:

var_dump($foo):
string(62) "{"action":"set","user":"123123123123","status":"OK"}"

现在我想在我的应用程序中解码json:

$data = json_decode($foo, true)

but it returns NULL:

var_dump($data):
NULL

I use php5. The Content-Type of the response from the webservice: "text/html; charset=utf-8" (also tried to use "application/json; charset=utf-8")

What could be the reason?

推荐答案

EDIT: Just did some quick inspection of the string provided by the OP. The small "character" in front of the curly brace is a UTF-8 B(yte) O(rder) M(ark) 0xEF 0xBB 0xBF. I don't know why this byte sequence is displayed as  here.

Essentially the system you aquire the data from sends it encoded in UTF-8 with a BOM preceding the data. You should remove the first three bytes from the string before you throw it into json_decode() (a substr($string, 3) will do).

string(62) "{"action":"set","user":"123123123123","status":"OK"}"
            ^
            |
            This is the UTF-8 BOM

As Kuroki Kaze discovered, this character surely is the reason why json_decode fails. The string in its given form is not correctly a JSON formated structure (see RFC 4627)

Json相关问答推荐

当整个数组存储为字符串时,如何在Oracle中获取json数组的大小

JOLT拉平数组

Vega-Lite时钟(使用Vega-Lite中的计时器)

我可以使用JQ来缩小数组中的json对象的范围吗?

将pyspark.sql.Rowtype数据转换为Json字符串,消除Azure Databricks NB中的值

报告重复的对象键

使用jq根据对象中键的值查找对象

如何按键过滤

打印与 JSON 和 PowerShell 中的模式匹配的子项的父项名称

嵌套存储在字符串变量中的 JSON 对象

如何使用 Google 表格应用程序脚本将 JSON 中的多个字段提取到 Google 表格中

如何在循环中传递列表(会话(字符串属性))以在 Gatling Scala 中创建批量 Json 请求

流编写器未写入 webapi 中的 JSON 文件

如何用 Xidel 正确读取这个 JSON 文件?

在 Android 中使用带有 post 参数的 HttpClient 和 HttpPost

从 VS 2017 Azure Function 开发中的 local.settings.json 读取值

严重:找不到媒体类型 = 应用程序/json、类型 = 类 com.jersey.jaxb.Todo、通用类型 = 类 com.jersey.jaxb.Todo 的 MessageBodyWriter

如何将单引号转义成双引号转成单引号

XML vs YAML vs JSON

使用 JSONArray 和 JSONObject 进行 Foreach