Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass JSON Data from PHP to Python Script

Tags:

python

json

php

I'd like to be able to pass a PHP array to a Python script, which will utilize the data to perform some tasks. I wanted to try to execute my the Python script from PHP using shell_exec() and pass the 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 hand off my array as the following to the 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 prints out the following to the browser:

["pizza", "french fries"]

This is a plain old string, not a list. My question is, how can I best treat this data like a list, or some kind of data structure which I can iterate through with the "," as a delimiter? I don't really want to output the text to the browser, I just want to be able to break down the list into pieces and insert them into a text file on the filesystem.

like image 789
azurepancake Avatar asked Jul 28 '16 03:07

azurepancake


2 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 Em L already mentioned :)

It works for me Cheers!

like image 171
bobkoo Avatar answered Nov 14 '22 19:11

bobkoo


You can base64 foods to string, then passed to the data to Python and decode it.For example:

import sys, base64
if len(sys.argv) > 1:
    data = base64.b64decode(sys.argv[1])
    foods = data.split(',')
    print(foods)
like image 1
Em L Avatar answered Nov 14 '22 18:11

Em L