繁体   English   中英

将数组 object 转换为 node.js 中的 json

[英]Converting array object into json in node.js

I am using python shell npm package to invoke the python scripts from node.js. 我的 python 脚本返回 json object 看起来像这样:

{"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();

Output:

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

我想既然结果已经是 object 我得到了错误。 所以我试图对结果进行字符串化并解析它。 那时我没有收到任何错误,但是当我通过调用结果访问时间戳等单个项目时。 时间戳,我越来越不确定。

谁能建议一种将其转换为 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM