我正在尝试编写一个脚本,该脚本使用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()错误,或者从抽搐发送的JSON对象有问题吗?
编辑:
我现在有了JSON对象:
{"access_token": "qwerty1235","refresh_token": "asdfghjkl=","scope": ["user_read"]}
如果尝试使用对其进行解码,则会json_decode()收到以下错误:Object of class stdClass could not be converted to string。有什么建议吗?
json_decode()
Object of class stdClass could not be converted to string
预先感谢您的任何帮助
您正在将JSON解码为数组。json_decode($json_object, true); 将返回一个数组
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)
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
请参阅文档,当为TRUE时,返回的对象将转换为关联数组。