json_decode() returning error “Notice: Trying to get property of non-object”

后端 未结 2 925
Happy的楠姐
Happy的楠姐 2020-12-06 13:04

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

相关标签:
2条回答
  • 2020-12-06 13:36

    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
    

    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
    

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

    0 讨论(0)
  • 2020-12-06 13:59

    You have set the second parameter ($assoc) of json_decode() to true, which means it's going to return an associative array instead of an object. You then tried to reference the object style. If you are setting the second parameter to true, you need to use the associative array style to access the stream content. It would be:

    $json_decoded['stream']
    

    If you set the $assoc parameter to false (or do not specify the parameter) then you can reference it as an object:

    $json_decoded->stream
    

    If you do var_dump on the $json_decoded variable you will see what it looks like. This is a good way to see what you are working with.

    0 讨论(0)
提交回复
热议问题