我正在传递一个JSON编码的字符串,json_decode()
并期望它的输出是一个对象类型,但我得到一个字符串类型.我怎样才能归还一个物体?
在文档中,以下内容返回一个对象:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
Run Code Online (Sandbox Code Playgroud)
但是,如果我json_encode()
首先调用字符串然后调用json_decode()
,则输出是字符串而不是对象:
$json = json_encode('{"a":1,"b":2,"c":3,"d":4,"e":5}');
var_dump(json_decode($json));
Run Code Online (Sandbox Code Playgroud)
这只是一个简化的例子.在实践中,我正在做的是通过AJAX将JSON编码的字符串推送到PHP.然而,它确实说明了将此编码的JSON字符串转换为我可以在PHP中读取的对象的问题,例如" $json->a
".
如何返回对象类型?
谢谢你的回复!这个问题的实际上下文是使用来自API的JSON响应.但是当我对这个响应执行json_decode并尝试访问类似的值 - $ json = json_decode(来自API的json响应); echo $ json->它给了我一个错误:类stdClass的对象无法转换为字符串
该函数json_encode
用于以JSON格式编码本机PHP对象或数组.
例如,$json = json_encode($arr)
其中$arr
是
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5,
);
Run Code Online (Sandbox Code Playgroud)
会返回字符串$json = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'
.在这一点上,你就不会需要重新用编码它json_encode
!
要获得你的阵列,只需这样做json_decode($json, true)
.
如果省略true
调用,则将使用JSON字符串中指定的各种属性json_decode
获取stdClass
替代实例.
有关更多参考,请参阅:
http://www.php.net/manual/en/function.json-encode.php
http://www.php.net/manual/en/function.json-decode.php
var_dump(json_decode($json, true));
Run Code Online (Sandbox Code Playgroud)
http://hk.php.net/manual/en/function.json-decode.php