json_decode()返回错误“注意:尝试获取非对象的属性"; [英] json_decode() returning error "Notice: Trying to get property of non-object"

查看:191
本文介绍了json_decode()返回错误“注意:尝试获取非对象的属性";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个脚本,该脚本使用cURL从远程位置(在本例中为twitch.tv)获取JSON文件(不要以为该部分太相关,尽管无论如何我还是最好提一下).出于示例目的,假设它返回的JSON对象存储在变量中后如下所​​示:

I am trying to write a script that gets a JSON file from a remote location (in this case being twitch.tv) using cURL (don't think that part is too relevant, though I better mention it anyway). For example purposes, lets say the JSON object it returns looks something like this after being stored in a variable:

$json_object = {"_links":{"self":"https://api.twitch.tv/kraken/streams/gmansoliver","channel":"https://api.twitch.tv/kraken/channels/gmansoliver"},"stream":null}

我访问"stream"属性,我已经尝试了以下代码:

I access the "stream" property, I have tried the follow code:

<?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中获取非对象的属性".

When I try this, I get the error "Notice: Trying to get property of non-object in D:\Servers\IIS\Sites\mysite\getstream.php on line 48".

我使用json_decode()错了,还是我从抽搐发送的JSON对象出了问题?

Am I using json_decode() wrong, or is there something wrong with the JSON object I am being sent from twitch?

我现在有了JSON对象:

I now have the JSON object:

{"access_token": "qwerty1235","refresh_token": "asdfghjkl=","scope": ["user_read"]}

如果尝试使用json_decode()对其进行解码,则会出现以下错误:Object of class stdClass could not be converted to string.有什么建议吗?

If I try to decode it using json_decode() I get the following error: Object of class stdClass could not be converted to string. Any advice?

在此先感谢您的帮助

推荐答案

您正在将JSON解码为数组. json_decode($json_object, true); 将返回一个数组

You're decoding the JSON into an array. json_decode($json_object, true); Will return an array

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)

If you remove the second parameter and run it as 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,则返回的对象将转换为关联数组.

See the documentation, When TRUE, returned objects will be converted into associative arrays.

这篇关于json_decode()返回错误“注意:尝试获取非对象的属性";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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