PHP-将JSON传递给Python脚本

时间:2019-05-10 06:33:03

标签: php python json

我的PHP中有这个数组:

$coordinates[] = [
        1 => [
            'x' => 300,
            'y' => 200,
            'w' => 400,
            'h' => 500,
        ]
    ];

    $coordinates[] = [
        2 => [
            'x' => 350,
            'y' => 100,
            'w' => 400,
            'h' => 500,
        ]
 ];

//Convert the array to JSON
$json = json_encode($coordinates);

//Invoke the python script:
$process = new Process("python3 /MyFile.py {$json}");
$process->run();

每个数组都是一个特定的页面,具有特定的坐标。

我想通过CLI将它们发送到Python脚本。在我的Python脚本中,我将其提取为:

import sys
import json

COORDINATES_JSON = sys.argv[1] if len(sys.argv) > 1 else None
COORDINATES = json.loads(COORDINATES_JSON)

但是,这给了我以下错误:

Error Output:
================
sh: sysctl: command not found
Traceback (most recent call last):
  File "MyPyFile.py", line 5, in <module>
    COORDINATES = json.loads(COORDINATES_JSON)
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您可以按照评论中的建议使用escapeshellarg($json)

// Invoke the python script:
$json = escapeshellarg($json);
$process = new Process("python3 /MyFile.py {$json}");
$process->run();

或者您可以将json放在文件中,然后在python中检索它。

file_put_contents('json_file.json', $json);

您还可以将json存储在内存,数据库或其他方式中,但我建议您坚持使用上面的第一个选项。