0

In my php script I've run the following

//PHP script to send json data to python
$t = new test();
$t->testname1 = $testname;
$t->jmx1=$jmx;
#$jsondata=json_encode($t);
$output=shell_exec('python /var/www/metro/run.py' . escapeshellarg(json_encode($jsondata)) );

Example of the json output as the following

"{"testname1":"fairul","jmx1":"1562638904.jmx"}"

I would like to use json.loads from the argument argv1 above in order to access it in python..

import sys, json

# Load the data that PHP sent us
try:
   data = json.loads(sys.argv[1])   
except:
   result = data['testname1']

# Send it to stdout (to PHP)
print json.dumps(result)

Not sure why i could only get NULL output

2
  • Have you seen what is in data? Commented Feb 17, 2014 at 16:02
  • Data looks okay....looks like php json.encode doesnt look right.. File "runtest.py", line 5 data = json.loads("{"testname1":"fairul","jmx1":"1562638904.jmx"}"() ^ SyntaxError: invalid syntax Commented Feb 17, 2014 at 16:37

1 Answer 1

1

You encoded the data twice; encode it just once:

$t->jmx1=$jmx;
$jsondata=json_encode($t);
$output=shell_exec('python /var/www/metro/run.py ' . escapeshellarg($jsondata) );

In Python, drop the blanked except handler, and move the setting result out of the exception handler. Here, I moved it into the try instead, catching either the IndexError when sys.argv[1] doesn't exist, ValueError thrown by a bad JSON string, TypeError when trying to index something that isn't a dictionary or the KeyError thrown for a missing key:

import sys, json

# Load the data that PHP sent us
try:
     data = json.loads(sys.argv[1])   
     result = data['testname1']
except (ValueError, TypeError, IndexError, KeyError) as e:
     print json.dumps({'error': str(e)})
     sys.exit(1)

print json.dumps(result)
Sign up to request clarification or add additional context in comments.

6 Comments

thanks...looks like its invalid syntax,I guess php json.encode doesnt give the output required by python json.loads.. File "runtest.py", line 5 data = json.loads("{"testname1":"fairul","jmx1":"1562638904.jmx"}"() ^ SyntaxError: invalid syntax
@JohnFai: That is not valid Python; you cannot nest quotes without proper escaping. If you are going to use a literal JSON value, use single quotes around it at the very least.
hmmm..thought PHP escapeshellarg will cater for this scenario
@JohnFai: You posted code in a comment that looks as if you are putting the JSON value straight into a literal. It doesn't look much like what I posted as an answer; are you still using sys.argv[1] here?
opss sorry, yes I put the JSON value straight as part of the test..in any case my sys.argv[1] doesnt seem to work yet
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.