代码之家  ›  专栏  ›  技术社区  ›  oliverbj

PHP-将JSON传递到Python脚本

  •  -3
  • oliverbj  · 技术社区  · 7 年前

    我的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();
    

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

    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)
    

    0 回复  |  直到 7 年前
        1
  •  0
  •   Peter    7 年前

    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存储在内存、数据库或其他方法中,但我建议您坚持使用上面的第一个选项。