How to access individual values from JWTAuth JSON data - php

I am attempting to extract JSON values from the return of a JWTAuth token 'user' key but cannot figure out how to address the inner keys using php. I have the following code:
if(!$user = JWTAuth::parseToken()->authenticate()){
abort(401);
}
else{
return response()->json(compact('user'));
}
}
And when including the proper token in the header, I do receive the user info
{"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"}}
However, I cannot figure out a way to address the individual values of the keys inside of the "user" key. How can I get the value of say the "user_firstname" key?
Thanks.
UPDATE
Using the Log::Info function within laravel to log data a local log. The following:
$json = response()->json(compact('user'));
$arr = json_decode($json, true);
Log::Info(var_dump($arr));
Log::Info($arr["user"]["user_firstname"]);
returns NULL for both the var dump and the multidimensional array call

You might want to learn about json_encode and json_decode to convert json objects into an array and vice versa. See manual here - http://php.net/manual/en/function.json-decode.php
$array = json_decode($json, true);
var_dump($array);
echo $array["user"]["user_firstname"];

$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>";
You could access array value :
echo $arr["user"]["user_firstname"]; //Prints Requester

Related

PHP get curl array results from inside a key value

I'm trying to get the access_token value from a curl response. The key value which is [0] renders out like so, {"access_token":"430f8a7d4f721a9e51e3558689ff28ec592923d2","expires_in":3600,"token_type":"Bearer","scope":null}.
However, I just need the value nested inside of access_token, which is 430f8a7d4f721a9e51e3558689ff28ec592923d2.
The output is rendered using this:
$cmd="curl -u testuser:123456 http://localhost/oauth2/server/token.php -d 'grant_type=client_credentials'";
exec($cmd,$result);
echo '<pre>'; print_r($result[0]); echo '</pre>';
How might go about doing this?
Btw, none of this is sensitive data. I'm just experimenting with oauth2.
Use the json_decode function on the results.
<?php
$json = '{"access_token":"430f8a7d4f721a9e51e3558689ff28ec592923d2","expires_in":3600,"token_type":"Bearer","scope":null}';
// Decode the JSON into an object
$decodedJson = json_decode($json);
$accessToken = $decodedJson->access_token;
var_dump($decodedJson,$accessToken);
// Decode the JSON into an array (note the true on the decode)
$decodedJson = json_decode($json,true);
$accessToken = $decodedJson['access_token'];
var_dump($decodedJson,$accessToken);
Encoding the json result, finds the subset.
$json = $result[0];
$json = json_decode($json, true);
echo $json['access_token'];

parsing a json array does not give me the values

below is my 'script.json' file with json array and i want the values of webUserid and webPassword
{
"totalSize":2,
"webUserId":"abc",
"webPassword":"def",
"operation":"send",
"testMode":true,
"records":[
{
"phoneNumber":"1908908399",
"message":"Happy Birthday",
"Id":"a0YL0000008QYunMAG",
"deviceId":"ABCDEFXABCDEF"
}
]
}
I tried below one but not getting the result
<?php
$jsonString=file_get_contents("script.json");
$decoded=json_decode($jsonString,true);
foreach($decoded->data as $name){
echo $name->totalSize;
}
?>
Zarif, try the below code, its working 100%......... :)
<?php
$jsonString=file_get_contents("script.json");
$decoded=array(json_decode($jsonString,true));
foreach($decoded as $name){
echo $name['totalSize'];
}
?>
There's no need for a foreach loop in your current example, as you only have one level.
Your main problem is you're trying to use the result of your json_decode as an object when you've previously stated you want the result as an associative array.
The 2nd param of json_decode specifies what format the return value is in, so as you've done
$decoded = json_decode($jsonString, true);
you'll receive an array, which you could access like
echo $decoded['totalSize'];
if you wanted to treat it as on object as you've done in your question, either state false or omit a 2nd param in json_decode (it's false by default anyway), and that'll let you do what you're trying to do:
$decoded = json_decode($jsonString);
$decoded->totalSize;
lets say that
$myJSON = yourPostedJSON.
$myJSON = json_decode($myJSON, true);
echo $myJSON['webUserId'];
echo $myJSON['webPassword'];

How to loop through this json decoded data in PHP?

I've have this list of products in JSON that needs to be decoded:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
Thanks!
To convert json to an array use
json_decode($json, true);
You can use json_decode() It will convert your json into array.
e.g,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
Try like following codes:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
Get Count
echo count($array); // 2
Did you check the manual ?
http://www.php.net/manual/en/function.json-decode.php
Or just find some duplicates ?
How to convert JSON string to array
Use GOOGLE.
json_decode($json, true);
Second parameter. If it is true, it will return array.
You can try the code at php fiddle online, works for me
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);

Processing Multidimensional JSON Array with PHP

This is the json that deepbit.net returns for my Bitcoin Miner worker. I'm trying to access the workers array and loop through to print the stats for my myemail#gmail.com worker. I can access the confirmed_reward, hashrate, ipa, and payout_history, but i'm having trouble formatting and outputting the workers array.
{
"confirmed_reward":0.11895358,
"hashrate":236.66666667,
"ipa":true,
"payout_history":0.6,
"workers":
{
"myemail#gmail.com":
{
"alive":false,
"shares":20044,
"stales":51
}
}
}
Thank you for your help :)
I assume you've decoded the string you gave with json_decode method, like...
$data = json_decode($json_string, TRUE);
To access the stats for the particular worker, just use...
$worker_stats = $data['workers']['myemail#gmail.com'];
To check whether it's alive, for example, you go with...
$is_alive = $worker_stats['alive'];
It's really that simple. )
You can use json_decode to get an associative array from the JSON string.
In your example it would look something like:
$json = 'get yo JSON';
$array = json_decode($json, true); // The `true` says to parse the JSON into an array,
// instead of an object.
foreach($array['workers']['myemail#gmail.com'] as $stat => $value) {
// Do what you want with the stats
echo "$stat: $value<br>";
}
Why don't you use json_decode.
You pass the string and it returns an object/array that you will use easily than the string directly.
To be more precise :
<?php
$aJson = json_decode('{"confirmed_reward":0.11895358,"hashrate":236.66666667,"ipa":true,"payout_history":0.6,"workers":{"myemail#gmail.com":{"alive":false,"shares":20044,"stales":51}}}');
$aJson['workers']['myemail#gmail.com']; // here's what you want!
?>
$result = json_decode($json, true); // true to return associative arrays
// instead of objects
var_dump($result['workers']['myemail#gmail.com']);

Reading multiple json values with php

I am trying to read certain values from a json string in php, I am able to do a simple json string with only one value such as
$json = '{"value":"somevalue"}';
Using this:
<?php
$json = '{"value":"somevalue"}';
$obj = json_decode(json_encode($json));
print $obj->{'value'};
?>
But when i try an get a value from the following json string it throws an error...
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
I validated the json on JSONlint but not sure how to access the values within this with php.
Thanks
You can try this:
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
//since $json is a valid json format you needn't encode and decode it again
$obj = json_decode($json);
print_r($obj->filed);
print_r($obj->rule);
You can pass true as a second parameter to json_decode() to get the results as an array
$my_arr = json_decode($json, true);
var_dump($my_arr);
Should help you. You can then step through the array as you would normally.
use var_dump to print out the object with all it's members and hierarchy. you should then be able to find the value you are looking for

Categories