我正在使用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/