Pass JSON data from PHP to Python Script

I would like to pass a PHP array to a Python script that will use the data to perform some tasks. I wanted to try to execute my Python script from PHP using shell_exec () and pass JSON data to it (which I’m completely new to).

$foods = array("pizza", "french fries"); $result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods))); echo $result; 

The "escapeshellarg (json_encode ($ foods)))" function seems to pass my array as follows in a Python script (I get this value if I echo the function:

 '["pizza","french fries"]' 

Then inside the Python script:

 import sys, json data = json.loads(sys.argv[1]) foods = json.dumps(data) print(foods) 

This browser displays the following:

 ["pizza", "french fries"] 

This is a simple old line, not a list. My question is: how can I best handle this data, such as a list or some kind of data structure that I can execute using "," as a separator? I really do not want to output the text to the browser, I just want to break the list into pieces and paste them into a text file in the file system.

+5
source share
3 answers

Had the same problem

Let me show you what I did

PHP:

 base64_encode(json_encode($bodyData)) 

then

 json_decode(shell_exec('python ' . base64_encode(json_encode($bodyData)) ); 

and in Python I have

 import base64 

and

 content = json.loads(base64.b64decode(sys.argv[1])) 

as already mentioned em l :)

It works for me Hooray!

+1
source

You can base64 foods into a string, then pass the data to Python and decode it. For instance:

 import sys, base64 if len(sys.argv) > 1: data = base64.b64decode(sys.argv[1]) foods = data.split(',') print(foods) 
0
source

If you have json: data = '["pizza", "french fries"]' and json.loads (data) does not work (what you need), then you can use: MyPythonList = eval (data) . eval takes a string and converts it to a python object

0
source

All Articles