如何从JWTAuth JSON数据

时间:2016-05-18 18:16:51

标签: php json laravel jwt

我正在尝试从返回JWTAuth令牌“用户”键中提取JSON值,但无法弄清楚如何使用php来解决内部键。我有以下代码:

if(!$user = JWTAuth::parseToken()->authenticate()){
        abort(401);
    } 

    else{
        return response()->json(compact('user'));

    }
}

如果在标题中包含正确的标记,我会收到用户信息

{"user":{"id":2,"organization_name":"test corp","user_type":"administrator","created_at":"2016-05-13 17:26:20","updated_at":"2016-05-13 17:26:20","user_firstname":"Requester","user_lastname":"chester","user_emailaddress":"requester@test.com","remember_token":null,"user_id":"uid-7e3a0e15-c97b-44b1-885d-4370f4d1"}}

但是,我无法找到一种方法来解决“用户”键内部键的各个值。如何获得“user_firstname”键的值?

感谢。

更新

使用laravel中的Log :: Info函数将数据记录到本地日志中。以下内容:

$json = response()->json(compact('user')); 
$arr = json_decode($json, true); 
Log::Info(var_dump($arr)); 
Log::Info($arr["user"]["user_firstname"]);

为var转储和多维数组调用

返回NULL

2 个答案:

答案 0 :(得分:2)

您可能想了解json_encode和json_decode以将json对象转换为数组,反之亦然。请参阅此处的手册 - http://php.net/manual/en/function.json-decode.php

$array = json_decode($json, true);
var_dump($array);
echo $array["user"]["user_firstname"];

答案 1 :(得分:0)

 $json = '{"user":{"id":2,"organization_name":"test corp","user_type":"administrator","created_at":"2016-05-13 17:26:20","updated_at":"2016-05-13 17:26:20","user_firstname":"Requester","user_lastname":"chester","user_emailaddress":"requester@test.com","remember_token":null,"user_id":"uid-7e3a0e15-c97b-44b1-885d-4370f4d1"}}';

 $arr = json_decode($json, true); //Converts JSON string into array

 echo "<pre>";
 print_r($arr);
 echo "<pre>";

您可以访问数组值:

 echo $arr["user"]["user_firstname"]; //Prints Requester