我正在使用 python shell npm 包从 node.js 调用 python 脚本。 我的 python 脚本返回 json 对象,如下所示:
{"timestamp":"2005-10-30 10:45:33","error_code":"0","error_code_string":"Passed","mac_address":"00:0D:6F:41:AA:4A"}
当我运行下面的代码时,我得到数组形式的结果:
const {PythonShell} = require("python-shell")
// import {PythonShell} from 'python-shell';
function Runpy(){
const options = {
mode: 'text',
pythonPath: 'C:/Users/xyz/AppData/Local/Programs/Python/Python38/python3',
pythonOptions: ['-u'],
scriptPath: 'D:/ABC',
args : ['-test=3','-scan=200']
};
PythonShell.run('test_runner.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
//parsed = results.toString();
//let parsedResult = JSON.parse(results);
console.log(results);
});
}
return Runpy();
输出:
results: ["{'timestamp': '2005-10-30 10:45:33', 'error_code': '0', 'error_code_string': 'Passed', 'mac_address': '00:0D:6F:41:AA:4A'}"]
[ '{\'timestamp\': \'2005-10-30 10:45:33\', \'error_code\': \'0\', \'error_code_string\': \'Passed\', \'mac_address\': \'00:0D:6F:41:AA:4A\'}' ]
当我尝试解析变量“结果”时,出现错误:
SyntaxError: Unexpected token ' in JSON at position 1
我认为由于结果已经是一个对象,所以我收到了错误。所以我尝试将结果字符串化并解析它。 然后我没有收到任何错误,但是当我通过调用结果访问时间戳等单个项目时。时间戳,我变得未定义。
谁能建议一种将其转换为 JSON 的方法吗?
最佳答案
问题来自于单个刻度'
。它们需要是双勾 "
才能成为有效的 json。您可以使用 replace
将 '
替换为 "
。
let results = ["{'timestamp': '2005-10-30 10:45:33', 'error_code': '0', 'error_code_string': 'Passed', 'mac_address': '00:0D:6F:41:AA:4A'}"];
results[0] = results[0].replace(/'/g, '"');
let parsed = JSON.parse(results[0])
console.log(parsed)
console.log(parsed.error_code)
关于javascript - 在node.js中将数组对象转换为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58638527/