JSON Decode (PHP) - php

how can I Select the value of "success" from that json?:
{
"response": {
"success": true,
"groups": [
{
"gid": "3229727"
},
{
"gid": "4408371"
}
]
}
}
Thats my current code:
$result = json_decode ($json);
$success = $result['response'][0]['success'];
echo $success;
Thank you.
Regards

Here You go... with a Quick-Test Here:
<?php
$strJson = '{
"response": {
"success": true,
"groups": [
{
"gid": "3229727"
},
{
"gid": "4408371"
}
]
}
}';
$data = json_decode($strJson);
$success = $data->response->success;
$groups = $data->response->groups;
var_dump($data->response->success); //<== YIELDS:: boolean true
var_dump($groups[0]->gid); //<== YIELDS:: string '3229727' (length=7)
var_dump($groups[1]->gid); //<== YIELDS:: string '4408371' (length=7)
UPDATE:: Handling the value of success within a Conditional Block.
<?php
$data = json_decode($strJson);
$success = $data->response->success;
$groups = $data->response->groups;
if($success){
echo "success";
// EXECUTE SOME CODE FOR A SUCCESS SCENARIO...
}else{
echo "failure";
// EXECUTE SOME CODE FOR A FAILURE SCENARIO...
}

You are almost near to solution. place "true" as second argument for json_decode().
Eg:
$result = json_decode ($json, true);
$result['response']['success'];` -> to get the value of success.

Related

How to get data from JSON after decoding

I am trying to get data from a JSON that's a bit complex for me.
How can I get the value in Amount or Transaction date
I can get the MerchantRequestID using this code
$mpesaResponse = file_get_contents('php://input');
$jsonMpesaResponse = json_decode($mpesaResponse, true);
$MerchantRequestID = $jsonMpesaResponse["Body"]["stkCallback"]["MerchantRequestID"];
// An accepted request
{
"Body":{
"stkCallback":{
"MerchantRequestID":"19465-780693-1",
"CheckoutRequestID":"ws_CO_27072017154747416",
"ResultCode":0,
"ResultDesc":"The service request is processed successfully.",
"CallbackMetadata":{
"Item":[
{
"Name":"Amount",
"Value":1
},
{
"Name":"MpesaReceiptNumber",
"Value":"LGR7OWQX0R"
},
{
"Name":"Balance"
},
{
"Name":"TransactionDate",
"Value":20170727154800
},
{
"Name":"PhoneNumber",
"Value":254721566839
}
]
}
}
}
}
At the moment it comes out blank what ever i try
You need to loop through your Item array.
<?php
$str = '
{
"Body":{
"stkCallback":{
"MerchantRequestID":"19465-780693-1",
"CheckoutRequestID":"ws_CO_27072017154747416",
"ResultCode":0,
"ResultDesc":"The service request is processed successfully.",
"CallbackMetadata":{
"Item":[
{
"Name":"Amount",
"Value":1
},
{
"Name":"MpesaReceiptNumber",
"Value":"LGR7OWQX0R"
},
{
"Name":"Balance"
},
{
"Name":"TransactionDate",
"Value":20170727154800
},
{
"Name":"PhoneNumber",
"Value":254721566839
}
]
}
}
}
}
';
$json = json_decode($str, true);
foreach($json['Body']['stkCallback']['CallbackMetadata']['Item'] as $index => $item_array_element){
if( $item_array_element['Name'] == 'Amount' ){
echo "Found Amount " . $item_array_element['Value'] . "\n";
}
else if( $item_array_element['Name'] == 'TransactionDate' ){
echo "Found TransactionDate " . $item_array_element['Value'] . "\n";
}
}
Output
Found Amount 1
Found TransactionDate 20170727154800

Edit JSON file using PHP

I'm trying to edit a JSON file using php, I've set up a little ReactJS app has form elements.
My JSON is as follows
[
{
"id": 1,
"Client": "client 1",
"Project": "project 1",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-1"
},
{
"id": 2,
"Client": "client 2",
"Project": "project 2",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-2"
},
{
"id": 3,
"Client": "client 3",
"Project": "project 3",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-3"
}
]
So far i have code to create a new "project" at the end of the file. My PHP is as follows
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$clientName = $_POST['clientName'];
$ProjectName = $_POST['projectName'];
$url = strtolower($_POST['url']);
$date = date('Y/m/d H:i:s');
$message = "";
$url = '../json/projects.json';
if( file_exists($url) )
if(file_exists('../json/projects.json'))
{
$current_data = file_get_contents('../json/projects.json');
$array_data = json_decode($current_data, true);
$extra = array(
'id' => count($array_data) + 1,
'Client' => $clientName,
'Project' => $ProjectName,
'StartDate' => $date,
'CompletedDate' => "",
'projectUrl' => $projectFileName + ".json"
);
$array_data[] = $extra;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents('../json/projects.json', $final_data))
{
$message = "sent";
}
else
{
$message = "notSent";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
What i can figure out is how to edit lets say "CompletedDate" value to todays date with a click of the button.
I have an hidden input field on my page that has the project ID in, so what I'm after is helping getting that id, matching it to the JSON, then editing the completed date that matches the ID.
This PHP will fire using ajax so i can pass the ID pretty easy.
Using similar code to what you already use, you can update the relevant data by using the ID as the index into the decoded JSON file. As ID 1 will be the [0] element of the array, update the [$id-1] element with the date...
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$id = 2; // Fetch as appropriate
$date = date('Y/m/d H:i:s');
$url = '../json/projects.json';
if( file_exists($url) )
{
$current_data = file_get_contents($url);
$array_data = json_decode($current_data, true);
$array_data[$id-1]['CompletedDate'] = $date;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents($url, $final_data))
{
$message = "updated";
}
else
{
$message = "notUpdated";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
You may need to tweak some of the bits - especially how the ID is picked up ($_GET?) and any messages you want.
I've also updated the code to make more consistent use of $url as opposed to hard coding it in a few places.

Using PHP to find specific entry in JSON URL response

I am trying to find out whether a user is part of a Steam group. To do this, I'm using Steam's Web API, and using URL:
https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE
To get a JSON response of all groups that a user is part of.
Now I want to find out if they're part of my specific group with ID: 1111111 using PHP.
How would one do that? Currently I have the code being decoded like so:
$groupid = "1111111";
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result, true);
This makes the $pretty variable contain the entire JSON response.
How would I use PHP to find the group ID in a response that looked like this?
{
"response": {
"success": true,
"groups": [
{
"gid": "4458711"
},
{
"gid": "9538146"
},
{
"gid": "11683421"
},
{
"gid": "24781197"
},
{
"gid": "25160263"
},
{
"gid": "26301716"
},
{
"gid": "29202157"
},
{
"gid": "1111111"
}
]
}
}
Can't figure it out.
Any help? :)
Use the below code to check whether user is exist in the response or not
$groupid = "1111111";
$is_exists = false;
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result, true);
foreach ($pretty['response']['groups'] as $key => $value) {
if($value['gid'] == $groupid) {
$is_exists = true;
break;
}
}
// check is_exists
Check that above variable $is_exists for true or false
$groupid = "1111111";
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList /v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result);
$s = $pretty->response->groups;
foreach($s as $value)
{
if((int) $groupid == $value->gid)
{
echo "Found";
}else
{
echo "Not found";
}
}

How to properly format data as JSON

I am working on hotels API, which needs to send data in JSON form,
But my JSON form is wrong and the API is not working.
My code is:-
$json = json_encode([
'RoomGuests' => [ json_encode(["NoOfAdults"=> 1,"NoOfChild"=> 0,"ChildAge"=> null])],
]);
And my output is :-
{
"RoomGuests": [
"{\"NoOfAdults\":1,\"NoOfChild\":0,\"ChildAge\":null}"
] }
And I want the result like this:-
{
"RoomGuests": [{
"NoOfAdults": 1,
"NoOfChild": 0,
"ChildAge": null
}], }
Please let me know how to solve this issue.
Use this
$json = json_encode([
'RoomGuests' => [["NoOfAdults"=> 1,"NoOfChild"=> 0,"ChildAge"=> null]],
]);
echo $json;
This will results into
{
"RoomGuests": [
{
"NoOfAdults": 1,
"NoOfChild": 0,
"ChildAge": null
}
]
}
For correct output instead of:
$json = json_encode([
'RoomGuests' => [ json_encode(["NoOfAdults"=> 1,"NoOfChild"=> 0,"ChildAge"=> null])],
]);
enough to make:
$json = json_encode([
'RoomGuests' => [ ["NoOfAdults"=> 1,"NoOfChild"=> 0,"ChildAge"=> null] ],
]);
json_encode will recursively encode all sub arrays. So it is enough to call only once.
This is my code which print the output in json format.You can edit it as per yours:
<?php
include_once('connect.php');
{
error_reporting( error_reporting() & ~E_NOTICE );
$id = $_GET['id'];
$name = $_GET['name'];
$date = $_GET['date'];
$select = "select * from details";
$sel = "select id,name from details";
$res = mysqli_query($con, $select);
$result = mysqli_query($con,$sel);
while($row = mysqli_fetch_object($res))
{
$output[] = $row;
}
if(empty($output))
{
print(json_encode("User doesn't exist"));
}
else{
while($col = mysqli_fetch_object($result))
{
$output[] = $col;
}
if(empty($output))
{
print(json_encode("User doesn't exits"));
}
else{
print(json_encode($output));
}
}
}
?>
<?php
$a = (object)[
'RoomGuests' => [
(object)["NoOfAdults"=> 1,"NoOfChild"=> 0,"ChildAge"=> null]
],
];
var_export(json_encode($a));
Result:
{"RoomGuests":[{"NoOfAdults":1,"NoOfChild":0,"ChildAge":null}]}

Problems storing nested JSON objects

Could anyone assist me with how I can pass one JSON object as a field to another without having quotes added? Basically I have a function that needs to be able to append a 'header' to a set of data pre parsed into JSON in some cases or just parse the data in others.
Problem is everything works fine until I try to pass a JSON object to be stored as a "payload" for a header, at which point the JSON becomes invalid because of the extra set of quotations attached.
The object that I am trying to use is:
{
"header": {
"table": "user",
"action": "insert",
"opType": "string",
"message": "Insert sucessful for user: 6",
"start of records": false,
"end of records": true
},
"data": "[
{
"id": "6",
"Surname": "Peter",
"Forename": "Kane",
"Email": "pkane#a.co.uk",
"Personal_Email": "p.kane#gmail.com",
"Home_Phone_No": "01216045429",
"Work_Phone_No": "087852489",
"Mobile_Phone_No": "77245455598",
"Address_Line_1": "1aplace",
"Address_Line_2": "thistown",
"Address_Line_3": "Someplace",
"Address_Line_4": "whereever",
"Post_Code": "W549AJ",
"Mode_ID": "44",
"Route_ID": "g12",
"image": ""
}
]"
}
The problem is the quotes after the "data" key and before the last curley brace without these everything validates fine.
As I've said Im using PHP Ive tried regex expressions substring etc but nothing seems to work.
my PHP is as follows:
public function dataToJSON($operationType, $table, $action, $data, $message, $header = true, $firstRecord = null) {
if ((!($operationType) === 'recordSet') and (!($operationType === 'error')) and (!($operationType === 'string') )) {
throw new Exception("Operation type:" . ' ' . $operationType . ' ' . 'passed to the dataToJSON function not recogonised');
}
if (!(is_null($firstRecord))) {
$isFirstRecord = $firstRecord;
$isLastRecord = !$firstRecord;
} else {
$isFirstRecord = false;
$isLastRecord = false;
}
if ($header) {
$jsonData = array('header' => array(
'table' => "$table",
'action' => "$action",
'opType' => "$operationType",
'message' => "$message",
'start of records' => $isFirstRecord,
'end of records' => $isLastRecord),
);
} else {
$jsonData = array();
}
$recordSet = array();
if ($operationType === 'recordSet') {
while ($row = mysql_fetch_assoc($data)) {
array_push($recordSet, $row);
}
if ($header) {
$jsonData ['data'] = $recordSet;
return json_encode($jsonData);
} else {
return json_encode($recordSet);
}
} else if (($operationType === 'error') || ($operationType === 'string')) {
if ($header) {
$jsonData ['data'] = $data;
return stripslashes(json_encode($jsonData));
} else {
return $data;
}
}
}
in order to use / parse json, it needs to be valid json... and those **"** chars make it invalid.
paste and process here to see what i mean: http://jsonformat.com/
A JSON object is nothing more than a mere string. To achieve what you are trying to achieve, you would probably need to decode and then re-encode your JSON string:
$jsonData['data'] = json_decode($data, TRUE);

Categories