【问题标题】:Parse the result of a python call with Node.js使用 Node.js 解析 python 调用的结果
【发布时间】:2022-01-08 15:48:45
【问题描述】:

我正在尝试使用 JSON.parse 解析我的 python 调用的结果。我在这里只提供我的 python 脚本(字典)的结果。

python 脚本

import json 

mydict =    {
  "brand": "Ford",
  "model": "Mustang",
  "licensePlate" : "O XXX YYY",
  "year" : 1964,
  "insured": {
                'lastname' : 'Snow', 
                'firstname' : 'John', 
                'adress' : 'Holiday street, 4 - Paradise'
             }
}
myjsonlist = json.dumps(mydict, indent = 4) 

print(myjsonlist) 

我的 javascript 调用 python 脚本并尝试解析结果(=来自 python 的字典)。目标是能够在 javascript 中使用这个字典。换句话说,我想在javascript中提取汽车的品牌,比如brandCar = resut.brand

//Import express.js module and create its variable.
const express=require('express');
const app=express();

//Import PythonShell module.
const {PythonShell} =require('python-shell');

//Router to handle the incoming request.

//Here are the option object in which arguments can be passed for the python_test.js.
let options = {
    mode: 'text',
    pythonOptions: ['-u'], // get print results in real-time
    scriptPath: '/mnt/c/Users/xxxxx/javascript/' //If you are having python script in same folder, then it's optional.
    //args: ['xxxx'] //An argument which can be accessed in the script using sys.argv[1]
};


PythonShell.run('pythonscript.py', options, function (err, result){
    if (err) throw err;
    // result is an array consisting of messages collected
    //during execution of script.
    console.log('result: ', result.toString());

    console.log(JSON.parse(result[0]));
});

在控制台中,我将此作为错误消息和结果

result:  {,    "brand": "Ford",,    "model": "Mustang",,    "licensePlate": "O XXX YYY",,    "year": 1964,,    "insured": {,        "lastname": "Snow",,        "firstname": "John",,        "adress": "Holiday street, 4 - Paradise",    },}
undefined:1
{

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at /mnt/c/Users/xxxxx/javascript/test2.js:62:19
    at PythonShell._endCallback (/mnt/c/Users/xxxxx/javascript/node_modules/python-shell/index.js:254:20)
    at terminateIfNeeded (/mnt/c/Users/xxxxx/javascript/node_modules/python-shell/index.js:209:39)
    at ChildProcess.<anonymous> (/mnt/c/Users/xxxxx/javascript/node_modules/python-shell/index.js:182:13)
    at ChildProcess.emit (events.js:400:28)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:282:12)

你能帮我解决这个问题吗?我使用适用于 Windows 10 的 Ubuntu Bash,我不知道这些信息是否相关......

【问题讨论】:

  • 试试JSON.parse(result.join('\n'))

标签: javascript python json parsing


【解决方案1】:

我终于解决了我的问题

1) 在 python 脚本中,我打印字典而不将其转换为 json 对象。当在 javascript 中调用 python 时,它会返回如下所示的字符串

result: {'brand': 'Ford', 'model': 'Mustang', 'licensePlate': 'O XXX YYY', 'year': 1964, 'insured': {'lastname': 'Snow', 'firstname': 'John', 'adress': 'Holiday street, 4 - Paradise'}}

此字符串包含单引号。

2) 在 javascript 中,我将所有单引号替换为双引号,以便将此字符串解析为 json 对象。

let parsedData = JSON.parse(JSON.stringify(result.join('\n')));
parsedData = parsedData.replace(/'/g, `"`); // replace the quote by the double quotes for parsing the string to a JSON object.
parsedData = JSON.parse(parsedData);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 2013-02-09
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多