-1

Hello before marking this as duplicate please note that i did tried this and this solution and they both did not worked for me. I am starting a child process in Node.JS and process starts a python file the python script at the end dumps the dictionary list into JSON which is valid as i parsed that json in this website. The main problem is that the collected json is not being parsed in Node.JS it shows the following error

SyntaxError: Unexpected token / in JSON at position 0

The code fragment is following

let output = '';
model = spawn("python3", ["./scanners/python/scan.py", code]);

model.stdout.on("data", function (data)
{
    output += data.toString();
    console.log(data.toString());
});

model.stderr.on("data", function (data)
{
    output += data.toString();
    console.log(data.toString());
});

model.on("close", function (exitCode)
{
   let result = JSON.parse(output.trim()); //exception is here
}

I tried the following methods to get rid of this but with no luck.

  1. Trimmed the output e.g. output.trim()
  2. Removed invisible control characters code taken from here
  3. Removed other trailing or leading characters code taken from here
  4. Tried with substring to not consider first character at position 0 then error changes e.g. invalid token v at position 0

kindly help, it is very frustrating

Zain Ul Abidin
  • 2,467
  • 1
  • 17
  • 29

1 Answers1

0

Basically i wasn't able to successfully remove invisible control characters that were causing the error so the next approach taken from here, this accepted answer does not show the removal but another approach that is to extract the actual json from the garbage string and then parse the JSON so that it becomes

let output = '';
model = spawn("python3", ["./scanners/python/scan.py", code]);

model.stdout.on("data", function (data)
{
    output += data.toString();
    console.log(data.toString());
});

model.stderr.on("data", function (data)
{
    output += data.toString();
    console.log(data.toString());
});

model.on("close", function (exitCode)
{
   output = output.trim().match(/[{].*.[}]/); //extract actual content from garbage e.g. JSON between [] or {}
   let result = JSON.parse(output.trim());
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
Zain Ul Abidin
  • 2,467
  • 1
  • 17
  • 29