Im in need of help outputting the json key with python. I tried to output the name "carl".
Python code :
from json import loads
import json,urllib2
class yomamma:
def __init__(self):
url = urlopen('http://localhost/name.php').read()
name = loads(url)
print "Hello" (name)
Php code (for the json which i made):
<?php
$arr = array('person_one'=>"Carl", 'person_two'=>"jack");
echo json_encode($arr);
the output of the php is :
{"person_one":"Carl","person_two":"jack"}
I'll just assume the PHP code works correctly, I don't know PHP very well.
On the client, I recommend using requests (installable through pip install requests):
import requests
r = requests.get('http://localhost/name.php')
data = r.json()
print data['person_one']
The .json method returns a Python dictionary.
Taking a closer look at your code, it seems you're trying to concatenate two strings by just writing them next to eachother. Instead, use either the concatenation operator (+):
print "Hello" + data['person_one']
Alternatively, you can use the string formatting functionality:
print "Hello {}".format(data['person_one'])
Or even fancier (but maybe a bit complex to understand for the start):
r = requests.get('http://localhost/name.php')
print "Hello {person_one}".format(**r.json())
try this:
import json
person_data = json.loads(url)
print "Hello {}".format(person_data["person_one"])
Related
is there any way to parse Python list in PHP?
I have data coming from python stored in mysql, something like this:
[{u'hello: u'world'}]
And need to use it in PHP script. The data is a valid JSON, only difference are those leading u'
So I can replace all u' with ' and then replace all ' with " to get it into json.
When I replace everything, if there is ' in the actual value, it is replaced by " as well and brakes the json.
So.. I tried a lot of stuff, but none of them was able to parse proper json thus my question -> Is there any way to parse Python generated list/json-like data in PHP? I dont mind using some third-party library or etc, just want to get the data parsed...
Thank you
If you have access to python, you can convert it to json from the command line.
Here's an example.
$ echo "{u'key': u'value'}" |\
python -c "import sys, json, ast; print(json.dumps(ast.literal_eval(sys.stdin.read())))"
{"key": "value"}
Here's a better formatted version of the python oneliner:
import sys, json, ast
data = ast.literal_eval(sys.stdin.read())
print(json.dumps(data))
By using ast.literal_eval instead of regular eval we can evaluate the python dictionary literal and not worry about potential code execution vulnerabilities.
I'm trying to send multiple values from PHP to Flash. I know how to send back one value, and that's by using PHP's print or echo, and then in flash using e.target.data., for example...
PHP:
print "resultMessage=$something";
Flash:
var resultText:TextField;
resultText.text = e.target.data.resultMessage;
The problem is when trying to receive 2 values; I've tried things like...
PHP:
print "resultNumber=$somethingNumber";
print "resultName=$somethingName";
Flash:
var flashNumber:TextField
flashNumber.text = e.target.data.resultNumber;
var flashName:TextField;
flashName.text = e.target.data.resultName;
But when I try that, flashNumber would end up as flashNumber and flashName mashed together, like 2Tom or 7Mary or something like that.
I tried printing <br> between the 2 values in PHP, but I still got the same result. I know that I can split the PHP into 2 PHP files and get a value from each one, but that would be a little ridiculous, since in my program I'll need to get many values.
Is there another way to send values from PHP to Flash, so that I can send more than 1 value? Or, is there a way to use print or echo to send more than 1 value?
Thank you very much in advance.
You can do this by outputting your data in a standard URL encoded variable format. (You need the ampersand that applications use to separate variables - otherwise it thinks everything after the first = is the value)
eg: print "resultNumber=$somethingNumber&resultName=$somethingName";
Then AS3 should automatically work the way you are trying.
You could also ouput XML or JSON as suggested by someone else.
JSON
PHP
<?php
$arr = array(somethingName, somethingNumber);
echo json_encode($arr);
?>
AS3
var jsonObj = JSON.parse(e.target.data);
trace(jsonObj.somethingName, jsonObj.somethingNumber);
XML
PHP
<?php
$string = <<<XML
<data>
<somethingName>
blah blah blah
</somethingName>
<somethingNumber>
12345
</somethingNumber>
</data>
XML;
$xml = new SimpleXMLElement($string);
echo $xml->asXML();
?>
AS3
myXML = new XML(e.target.data);
trace(myXML.somethingName, myXML.somethingNumber);
Better use some data formatting instead of passing data as pure text - XML or JSON is a good idea.
There is a web application written in PHP and HTML. What I want is to filter a users input for a variety of cases and sanitize it. For example, I want to compare the input from a form (string) with a list of allowed strings and depending if it is right or wrong to trigger the suitable PHP function to handle this.
My question is how to bind the user input with the python script and then the outcome of this python script as an input for PHP?
thanks
You can call the Python script from your PHP file as a shell command, passing it JSON-formatted arguments. Then have the Python script output the response (also JSON encoded) and have the PHP file capture that. Here's an example I used recently, cobbled together from the links below:
PHP file:
$py_input = ... // Your data goes here.
// Call the Python script, passing it the JSON argument, and capturing the result.
$py_output = shell_exec('python script.py ' . escapeshellarg(json_encode($py_input)));
$py_result = json_decode($py_output);
Python file:
import json
php_input = json.loads(sys.argv[1]) # The first command line argument.
# Do your thing.
php_output = ... # Whatever your output is.
print json.dumps(php_output) # Print it out in JSON format.
Passing a Python list to php
executing Python script in PHP and exchanging data between the two
I use exec function calling python script from PHP script. Python writes to standard output two strings which I need in PHP script. The problem is that in these strings could be end of line characters \n ( so formally there are many lines in output), and according to exec manual array $output will contain
each line in it. What is elegant way to escape \n characters so that $output will contain only two string I want and no post processing of these two string needed?
EDIT: I can change python script.
Print the output in an easily parsable format, such as JSON, and parse it from PHP. For example, instead of:
print foo
print bar
Use something like:
import json
print json.dumps([foo, bar])
You read the JSON output form PHP and decode it using json_decode($output) into the desired array.
There really is nothing you can do about this outside of changing the way the python script outputs.
It is really easy to clean the returned data though.
exec('yourcommand', $array);
array_walk($array, function($value, $key) {
return trim($value);
});
Firstly, I have search Stack Overflow for the answer, but I have not found a solution that works.
I am using an MVC framework (yii) to generate some views and throw them in an array. Each view is a card, and I have an array of cards ($deck) as well as an array of arrays of cards ($hands, the list of hands for each player). I'm simply trying to set a javascript variable on the front-end to store the hands created in PHP. My view has, it is worth noting, multiple lines. In fact, my current test view consists only of:
test
test
I therefore used json_encode, but it's giving me the following error when I use $.parseJSON():
Uncaught SyntaxError: Unexpected token t
I read elsewhere that it is required (for whatever reason) to use json_encode twice. I have tried this, but it does not help.
With a single json_encode, the output of echoing $hands (followed by an exit) looks pretty healthy:
[["test\ntest","test\ntest","test\ntest","test\ntest", etc...
But when I do not exit, I get a syntax error every time.
Edit: Here is a sample of my code. Note that $cards is an array of HTML normally, but in my simplified case which still errors, includes only the two lines of 'test' as mentioned above.
$deck = array();
foreach ($cards as $card) {
$deck[] = $this->renderPartial('/gamePieces/cardTest',
array('card'=>$card), true);
}
$hands = Cards::handOutCards($deck, $numCards , $numPlayers);
$hands = json_encode($hands);
echo $hands; exit;
With JavaScript, I am doing the following:
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
It errors on page load.
Any help would be appreciated!
Thanks,
ParagonRG
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
This will result in something like:
var hands = $.parseJSON('{"foobar":"baz'"}');
If there are ' characters in the encoded string, it'll break the Javascript syntax. Since you're directly outputting the JSON into Javacript, just do:
var hands = <?php echo json_encode($hands); ?>;
JSON is syntactically valid Javascript. You only need to parse it or eval it if you receive it as a string through AJAX for instance. If you're directly generating Javascript source code, just embed it directly.