简体   繁体   English

在 PHP 和 Python 之间传递 JSON

[英]Passing a JSON between PHP and Python

I need to pass data from a PHP page to a Python script and back.我需要将数据从 PHP 页面传递到 Python 脚本并返回。 I do it with a form that reminds to a page with this PHP code:我用一个表单来提醒这个 PHP 代码的页面:

<html>
    <body>
        <h1>Project</h1>
        <h2>Results</h2>

    </body>
</html>

<?php 
    $myHotel->name = $_POST["NAME"];
    $hotel_data = json_encode($myHotel); ;
    $command = escapeshellcmd("/var/www/html/test.py $hotel_data");
    $resultAsString = exec($command);
?>

The JSON is sent back from the Python script: JSON 从 Python 脚本发回:

#!/usr/bin/env python
import sys
import json

print(sys.argv[1]);

The problem, is that i send a JSON string like this:问题是我发送了一个 JSON 字符串,如下所示:

{"name":"Hotel Roma Sud"}

And I receive something like this:我收到这样的东西:

{name:Hotel Roma Sud}

How can I receive a JSON string or manage to have one?我怎样才能收到 JSON 字符串或设法拥有一个? I tried with exec(), json_encode, json_decode... Thanks我尝试使用 exec()、json_encode、json_decode ... 谢谢

You need to modify the script calling the command to avoid " getting parsed out by the bash - in order to give Python correct JSON string the argument should look like this - python test.py "{""name"":""Hotel Roma Sud""}" - this way Python receives '{"name":"Hotel Roma Sud"}' for argv[1] which you can parse with json.loads . It's not very clean solution though, so I'd probably save the JSON string to a file from PHP and then load the contents of the file in Python, deleting the file afterwards if necessary. You need to modify the script calling the command to avoid " getting parsed out by the bash - in order to give Python correct JSON string the argument should look like this - python test.py "{""name"":""Hotel Roma Sud""}" - 这样 Python 会收到'{"name":"Hotel Roma Sud"}'argv[1] ,您可以使用json.loads解析它。虽然它不是很干净的解决方案,所以我可能会保存将 JSON 字符串从 PHP 加载到文件中,然后将文件的内容加载到 Python 中,如有必要,然后删除该文件。

I've found an elegant solution, hope it can be useful for anyone:我找到了一个优雅的解决方案,希望它对任何人都有用:

PHP file: PHP 文件:

<p>Test JSON</p>
<?php
$loc = "Roma Sud";
$hotel = array("Name"=>$loc,"Stars"=>"3");
$param = base64_encode(json_encode($hotel));
$result = shell_exec("/var/www/html/test-json/test.py $param");
// echo "<strong>Hotel Name: </strong>";
$obj = json_decode($result);
print "<strong>Hotel Name: </strong>" . $obj->Name . "<br/>";
print "<strong>Stars: </strong>" . $obj->Stars . "<br/>";
?>

Python file: Python 文件:

#!/usr/bin/env python
import sys
import json
import base64
    
content = json.loads(base64.b64decode(sys.argv[1]))
print(json.dumps(content))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM