代码之家  ›  专栏  ›  技术社区  ›  DEVPROCB

如何访问此json响应中的属性?

  •  1
  • DEVPROCB  · 技术社区  · 8 年前

    我正在执行一个curl请求并获得一个返回json响应的响应。以下是发送回响应后的代码。

    答复: “零替换了实数标记”

    {"success":true,"result":{"token":"000000000","serverTime":1471365111,"expireTime":1471365411}}1
    

    使用的代码(用于测试)和访问属性: $json=json_decode($result); print_r($json);//打印Json响应

    $firsttry = $json->result['token']; //Access Property results in error :Trying to get property of non-object
    $secondtry = $json['token']; 
    
    echo $firsttry.'<br>';//Code can't continue because of error from $firsttry.
    print_r( $secondtry.'<br>');//Nothing Prints at all
    

    我确实注意到了一个奇怪的异常,它在末尾打印了一个1,就像我看到了一样

    json_encode($json);
    

    返回响应用“true”替换字符串末尾的响应

    也许我错过了一些简单的东西?

    按要求完整测试代码

    $url = "https://website.com/restapi.php";
    //username of the user who is to logged in. 
    $userName="adminuser"; //not real user
    
    $fields_string; //global var
    
    
    $fields = array( //array will have more in the future
    'username' => urlencode($userName)
     );
    
    //url-ify the data for the POST
    foreach($fields as $key=>$value) { global $fields_string;
    $fields_string .= $key.'='.$value.'&'; }
    rtrim($fields_string, '&');
    
    //open connection
    $ch = curl_init();
    
    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL,         $url.'?'.$fields_string.'operation=getchallenge');
    curl_setopt($ch,CURLOPT_POST, count($fields));
    
    //execute post
    $result = curl_exec($ch);
    
    //close connection
    curl_close($ch);
    
    3 回复  |  直到 8 年前
        1
  •  2
  •   TheGentleman    8 年前

    json_decode() ,默认情况下使子对象成为 stdClass 对象而不是数组,除非它们是显式数组。

    $firsttry = $json->result->token;
    
        2
  •  0
  •   BeetleJuice    8 年前

    var_dump显示数据类型。自从 result 本身是一个对象,使用 -> 而不是 []

    $response = '{"success":true...}'
    $json = json_decode($response); //var_dumping this will show you it's an object
    echo $json->result->token; // 000000000
    
        3
  •  0
  •   DEVPROCB    8 年前

    我解决了这个问题。在“卷曲选项”中,我没有

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    

    一旦我把这个放到@GentelmanMax解决方案中,对我来说很管用,但问题在于curl响应直接响应,在这里,当返回传输发送回php可以使用的字符串时,它允许json_decode()按原样运行。我知道这很简单。