I am using python shell npm package to invoke the python scripts from node.js. My python Script returns json object which looks like this:
{"timestamp":"2005-10-30 10:45:33","error_code":"0","error_code_string":"Passed","mac_address":"00:0D:6F:41:AA:4A"}
When i run the below code i get the results in the form of array:
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\'}' ]
When I try to parse the variable 'results' i get the error:
SyntaxError: Unexpected token ' in JSON at position 1
I thought since results are already an object I am getting the error. So I tried to stringify the results and parse it. I am not getting any error then, but when I access individual items like timestamps by calling results. timestamp, I am getting as undefined.
Can anyone please suggest a way to convert this into JSON?
"to'?