我正在尝试编写一个脚本,该脚本使用 cURL 从远程位置(在本例中为 twitch.tv)获取 JSON 文件(不要认为该部分太相关,尽管我还是最好提一下)。例如,假设它返回的 JSON 对象在存储在变量中后看起来像这样:
$json_object = {"_links":{"self":"https://api.twitch.tv/kraken/streams/gmansoliver","channel":"https://api.twitch.tv/kraken/channels/gmansoliver"},"stream":null}
我访问“流”属性,我尝试了以下代码:
<?php
$json_object = {"_links":{"self":"https://api.twitch.tv/kraken/streams/gmansoliver","channel":"https://api.twitch.tv/kraken/channels/gmansoliver"},"stream":null}
$json_decoded = json_decode($json_object, true);
echo $json_decoded->stream;
?>
当我尝试此操作时,出现错误“注意:尝试在第 48 行获取 D:\Servers\IIS\Sites\mysite\getstream.php 中非对象的属性”。
我是否使用了 json_decode() 错误,或者我从 twitch 发送的 JSON 对象有问题吗?
编辑:
我现在有 JSON 对象:
{"access_token": "qwerty1235","refresh_token": "asdfghjkl=","scope": ["user_read"]}
如果我尝试使用
json_decode()
对其进行解码,则会出现以下错误: Object of class stdClass could not be converted to string
。有什么建议吗?在此先感谢您的帮助
最佳答案
您正在将 JSON 解码为一个数组。 json_decode($json_object, true);
将返回一个数组
array (size=2)
'_links' =>
array (size=2)
'self' => string 'https://api.twitch.tv/kraken/streams/gmansoliver' (length=48)
'channel' => string 'https://api.twitch.tv/kraken/channels/gmansoliver' (length=49)
'stream' => null
如果删除第二个参数并将其作为
json_decode($json_object)
运行object(stdClass)[1]
public '_links' =>
object(stdClass)[2]
public 'self' => string 'https://api.twitch.tv/kraken/streams/gmansoliver' (length=48)
public 'channel' => string 'https://api.twitch.tv/kraken/channels/gmansoliver' (length=49)
public 'stream' => null
See the documentation ,当为 TRUE 时,返回的对象将被转换为关联数组。