json_decode返回字符串类型而不是对象 [英] json_decode returns string type instead of object

查看:667
本文介绍了json_decode返回字符串类型而不是对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将JSON编码的字符串传递给json_decode(),并期望其输出为对象类型,但是却获得了字符串类型.如何返回对象?

I'm passing a JSON-encoded string to json_decode() and am expecting its output to be an object type, but am getting a string type instead. How can I return an object?

在文档中,以下代码返回一个对象:

In the docs, the following returns an object:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));

但是,如果我先json_encode()个字符串然后调用json_decode(),则输出为字符串而不是对象:

However, if I json_encode() the string first and then call json_decode(), the output is a string and not an object:

$json = json_encode('{"a":1,"b":2,"c":3,"d":4,"e":5}');
var_dump(json_decode($json));

这只是一个简化的示例.在实践中,我正在通过AJAX将JSON编码的字符串推送到PHP.但是,它确实说明了将编码后的JSON字符串转换为我可以在PHP中读取的对象的问题,例如"$json->a".

This is just a simplified example. In practice what I'm doing is pushing a JSON-encoded string to PHP via AJAX. However it does illustrate the problem of converting this encoded JSON string to an object I can read in PHP, e.g., "$json->a".

如何返回对象类型?

感谢您的答复! 该问题的实际上下文是使用来自API的JSON响应. 但是当我对这个响应进行json_decode并尝试访问-$ json = json_decode(API的json响应)之类的值时; 回声$ json-> a 它给了我一个错误:stdClass类的对象无法转换为字符串

thanks for the replies ! The actual context for this question was am using a JSON Response from a API. But when I do the json_decode to this response and try to access the values like - $json=json_decode(json response from API); echo $json->a it gives me a error: Object of class stdClass could not be converted to string

推荐答案

函数json_encode用于以JSON格式编码本机PHP对象或数组.

The function json_encode is used to encode a native PHP object or array in JSON format.

例如$json = json_encode($arr)其中$arr

$arr = array(
  'a' => 1,
  'b' => 2,
  'c' => 3,
  'd' => 4,
  'e' => 5,
);

将返回字符串$json = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'.此时,您不需要再次使用json_encode对其进行编码!

would return the string $json = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'. At this point, you do not need to encode it again with json_encode!

要获取阵列,只需执行json_decode($json, true).

To obtain your array back, simply do json_decode($json, true).

如果在对json_decode的调用中省略了true,则将获取stdClass的实例,而该实例具有JSON字符串中指定的各种属性.

If you omit the true from the call to json_decode you'll obtain an instance of stdClass instead, with the various properties specified in the JSON string.

有关更多参考,请参见:

For more references, see:

http://www.php.net/manual/zh/function.json-encode.php

http://www.php.net/manual/zh/function.json-decode.php

这篇关于json_decode返回字符串类型而不是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆