Reputation: 189
I am having a hard time parsing an array in python when the array is coming from a php file.
test.php
$count = 3;
$before_json = array("qwe","wer","ert");
print_r($before_json );
$after_json = json_encode($before_json );
echo $after_json;
$command = escapeshellcmd("test.py $after_json $count");
$output = shell_exec($command);
echo $output;
print_r($before_json ); will display - Array ( [0] => qwe [1] => wer [2] => ert )
echo $after_json; will display - ["qwe","wer","ert"]
py.test
import sys
after_json = sys.argv[1]
count = sys.argv[2]
print (device_id)
print (after_json) will print - [qwe,wer,ert]
print (after_json[1]) will print - q
How can I have it print out any of the 3 items that are in after_json?
Upvotes: 1
Views: 3697
Reputation: 833
after_json=after_json[1:-1].split(",")
while after_json
is ["qwe","wer","ert"]
u can omit first and last character and then split remaining string wich can be split by comma
Upvotes: 0
Reputation: 7297
The problem you are seeing is the lack of parsing of JSON in Python, as stated by rickdenhaan.
However you also want to make sure to quote your string correctly, when you send it to the shell interpreter in this line:
$command = escapeshellcmd("test.py $after_json $count");
If we manually fill in the variables, we will get the following result (not sure what $count
is, so I just assumed a value of 3):
$command = escapeshellcmd("test.py [\"qwe\",\"wer\",\"ert\"] 3");
This only works, because there are no spaces in the formatting of your JSON. As soon as you have spaces in the parsed JSON, your shell call of the Python script will totally fail. It's also a security nightmare, because each of the elements of the JSON array can lead to arbitrary code execution in your shell.
You have to escape your arguments when you pass them to the shell. For this, you should use the function escapeshellarg
.
This is probably what you want to do instead:
$escaped_json = escapeshellarg($after_json)
$command = escapeshellcmd("test.py $escaped_json $count");
If you are not 100% sure that $count
is an integer, you should also call escapeshellarg
on that parameter.
Upvotes: 1
Reputation: 11328
You still need to parse the JSON string in Python. You can use the json
module for that:
import sys, json
after_json = sys.argv[1]
count = sys.argv[2]
parsed_data = json.loads(after_json)
print (parsed_data[0]) # will print "qwe"
Upvotes: 0