I'm trying to use PHP for a command-line script. I pass in a json string to it, and I'm trying to read the values out but getting an error when I do echo $user_inputs["foo"];, why is this? Am I forgetting something about json_decode, or is it about using STDIN?
my_test.php
// Get the STDIN.
$stdin = fopen('php://stdin', 'r');
// Initialize user_inputs_json which will be the entire stdin.
$user_inputs_json = "";
// Read all of stdin.
while($line = fgets($stdin)) {
$user_inputs_json .= $line;
}
// Create the decoded json object.
$user_inputs = json_decode($user_inputs_json);
// Try to echo a value. This is where I get my error (written out below).
echo $user_inputs["foo"];
fclose($stdin);
Run this in command line to pass JSON into it:
$ echo '{"foo":"hello world!", "bar": "goodnight moon!"}' | php my_test.php
I get this error:
Fatal error: Cannot use object of type stdClass as array in /Users/don/Desktop/my_test.php on line 20
By default json_decode converts JSON string into PHP object. If you want to get PHP array, use the second parameter of json_decode:
$user_inputs_array = json_decode($user_inputs_json, true);
If you need to always handle the passed in JSON as an array, set the second json_decode parameter to true to force it to decode as an array:
$user_inputs = json_decode($user_inputs_json, 1);
Related
Output when success
string(66)
"{"status":true,"message":"success","data":{"amountDue":"-504.20"}}"
Output when error
string(119) "{"status":false,"message":"An error occured while getting
full subscriber profile: Subscription not found MPP servers"}"
How should I write in php to get the amount due from the output? I am new to REST api. Can someone show me ? Thank you
That is a JSON-encoded response. Use json_decode() to convert the string back into an array, and then access the array element:
$output = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$results = json_decode($output,true);
if($results["status"])
{
echo "Success! Data: " . print_r($results,true);
}
I assume that you can at least send proper request to the endpoint and you are able to capture the response.
You receive a json string which must be parses so if:
$response = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$responseArray = json_decode($response, true);
Then you will get a responseArray as associated array (the second parameter) so you can get amount due like that
$amountDue = $responseArray['data']['amountDue'];
You could also parse json data into an StdClass which turn all fields in json into an object's property. To do that abandon the second parameter in json_decode function
$resultObj = json_decode($response);
$amountDue = $resultObj->data['amountDue'];
All depends on your requests.
To read more about json_decode try documentation
I am working with the SendGrid PHP Library (https://sendgrid.com/docs/Integrate/Code_Examples/php.html).
The response is sent ass JSON - e.g. should be something like:
{"message":"success"}
I can send a simple email via:
<?php
$root="../../";
require $root . 'vendor/autoload.php';
$sendgrid = new SendGrid($SendGrid);
$email = new SendGrid\Email();
$email
//->addTo('you#me.com')
->addTo('you#me.com')
->setFrom('me#bar.com')
->setSubject('Subject goes here')
->setText('Hello World!')
->setHtml('<strong>Hello World!</strong>')
;
$res = $sendgrid->send($email);
?>
When I display the output of $res e.g. using PHP-REF (https://github.com/digitalnature/php-ref) I can see that it looks like this:
It appears the response is an Object - presumably JSON?
However, I can't access the data as JSON because if I try this:
$newtxt = json_decode($res);
I get this error:
Warning: json_decode() expects parameter 1 to be string, object given in C:\xampp\htdocs\jim\001-jimpix\contact_old\test-send-grid.php on line 24
And if I try this:
$j_array = json_decode($res, true);
I get the same error.
I can hard code the "$res" value as:
$res = "{\"message\":\"success\"}";
And then that works.
However, I can't work out how to access the JSON returned by SendGrid.
I've tried various things like:
$res = json_decode(json_encode($res),TRUE);
Presumably there is a way to access the JSON returned by SendGrid so I can access the JSON data.
But I don't know how?
As you can see from the PHP-REF response, $res is not the raw JSON.
You can access the result simply by using $res->getBody(). This will give you the parsed JSON from SendGrid.
You do not need to json_decode this.
I am trying to write a php code that takes coefficients from a html form, sends them to a python algorithm that returns a json object. That object is a list of player names, basically {"Ji" : "Firstname Lastname"} for i from 1 to 15.
The python code (interface.py) I have to create this json is :
import json
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]=joueur['nom']
out=json.dumps(output)
print(out)
best_team is a list of player dictionnaries with data on them. My player names don't involve any non ASCII characters or whatever.
My php code is the following :
$command = "python interface.py";
$command .= " $coeff1 $coeff2 $coeff3 $coeff4 $coeff5 $coeff6 $coeff7 $coeff8 $coeff9 $coeff10 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
$data = fread($pid, 256);
$data= json_decode($data) ;
echo $data->J1;
flush();
ob_flush();
echo "<script>window.scrollTo(0,99999);</script>";
usleep(100000);
}
pclose($pid);
I call the coefficients from the html and then send back the results via a js file.
But I just get the following error : Notice: Trying to get property of non-object.
Nothing wrong with the js file because if I try instead :
$string = '{"foo": "bar", "cool": "attributlong"}';
$result = json_decode($string);
echo $result ->cool;
It works.
Also if I have instead in my python file :
out={"foo":"bar","word":"longerthaneightcharacters"}
out=json.dumps(out)
print(out)
It works as well (replacing J1 by word in php code of course).
And funny enough, if i have in python:
output={}
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]="short"
output["J%s"%(i)]=str(output["J%s"%(i)])
out=json.dumps(output)
print(out)
It works, and if I replace "short" by "longerthaneightcharacters" it doesn't work anymore.
So basically my question is, why is there a maximum number of characters in my output loop and how can I bypass it ? Thanks, I am very confused.
I've some JSON data in a javascript file
Data is build using javascript object literal notation;
var CMS = window.CMS = window.CMS || {};
CMS.Data = window.CMS.Data = window.CMS.Data || {};
CMS.Data['LANGUAGES'] = [
{id:"chi", value:"Chinese"},
{id:"spa", value:"Spanish"},
{id:'eng', value:"English"},
{id:"hin", value:"Hindi"},
];
CMS.Data['AGE_RANGE'] = [{id:'18', value:"18"}, {id:'25', value:"25"}, {id:'30', value:"30"}, {id:'35', value:"35"}, {id:'40', value:"40"}, {id:'50', value:"50"}, {id:'60', value:"60"}, {id:'70', value:"70"}, {id:'80', value:"80"}, {id:'90', value:"90"}, {id:'100', value:"100"}];
CMS.Data['HEIGHT_RANGE'] = [{id:'140-150', value:"140-150"}, {id:'150-160', value:"150-160"}, {id:'160-170', value:"160-170"}, {id:'180-190', value:"180-190"}];
Complete data is available at https://gist.github.com/mithunqb/675613fe985fe2afbbcf
I need to make it available in PHP array.
I cannot simply load the content and apply json_decode
$json_string = file_get_contents('data.json');
$json_array = json_decode($json_string, true);
As the content inside the json file is not actually a valid JSON string, the above operation will result NULL;
How can I do this?
If the JSON string is not valid then there is no way to convert it to PHP array. Not a chance at any circumstances. It's obvious.
You must provide a valid JSON string.
I have a python script that returns a json object. Say, for example i run the following:
exec('python /var/www/abc/abc.py');
and it returns a json object, how can i assign the json object as a variable in a php script.
Example python script:
#!/usr/bin/python
import sys
def main():
data = {"Fail": 35}
sys.stdout.write(str(data))
main()
Example PHP script:
<?php
exec("python /home/amyth/Projects/test/variable.py", $output, $v);
echo($output);
?>
The above returns an empty Array. Why so ?
I want to call the above script from php using the exec method and want to use the json object returned by the python script. How can i achieve this ?
Update:
The above works if i use another shell command, For Example:
<?php
exec("ls", $output, $v);
echo($output);
?>
Anyone knows the reason ?
If the idea is you'll have a Python script which prints JSON data to standard out, then you're probably looking for popen.
Something like...
<?php
$f = popen('python /var/www/abc/abc.py', 'r');
if ($f === false)
{
echo "popen failed";
exit 1;
}
$json = fgets($f);
fclose($f);
...will grab the output into the $json variable.
As for your example Python script, if the idea is you're trying to convert the Python dictionary {"tests": "35"} to JSON, and print to standard out, you need to change loads to dumps and return to print, so it looks like...
import simplejson
def main():
data = simplejson.dumps({"tests": "35"})
print data
main()