Reputation: 167
I have a Python script that outputs a bunch of text to PHP using print
and shell_exec()
. I also have to send a dictionary between the two, to store some script information. Here is a simplified version of my code:
import json
# Lots of code here
user_vars = {'money':player.money}
print(user_vars)
print(json.dumps(user_vars))
which outputs (in PHP):
{'money': 0} {"money": 0}
So the same thing, except JSON has double quotes.
This is the code I would use if I wanted to use JSON (print(json.dumps(user_vars))
, which outputs {"money": 0}
, note double quotes) to transfer data:
<?php
$result = shell_exec('python JSONtest.py');
$resultData = json_decode($result, true);
echo $resultData["money"];
?>
I have two questions:
print(user_vars)
instead of
print(json.dumps(user_vars))
, or vice versa?user_vars
/json.dumps(user_vars)
without it being seen in the final PHP page without having to dump them in an actual .json
file? Or am I going about this problem in the wrong way?My code was based on the question here.
Upvotes: 4
Views: 2005
Reputation: 167
This code does the trick.
import json
data = {'fruit':['oranges', 'apples', 'peaches'], 'age':12}
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
<?php
$string = file_get_contents("data.json");
$json_a = json_decode($string, true);
echo $json_a['age']; # Note that 'fruit' doesn't work:
# PHP Notice: Array to string conversion in /var/www/html/JSONtest.php on line 4
# Array
?>
This method only works with strings, but it does solve my problem, and I can get around not using lists/arrays.
Upvotes: 2