【发布时间】: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