Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

php - json_decode() returning error "Notice: Trying to get property of non-object"

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}

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;
?>

When I try this, I get the error "Notice: Trying to get property of non-object in D:ServersIISSitesmysitegetstream.php on line 48".

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

Edit:

I now have the JSON object:

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

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?

Thanks in advance for any help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...