问题描述
您好,在将其标记为重复之前,请注意我确实尝试过 this 和 this 解决方案,但它们都对我不起作用。我正在 Node.JS 中启动一个子进程,进程启动一个 python 文件,最后的 python 脚本将字典列表转储到 JSON 中,当我在这个网站上解析该 json 时,它是有效的。主要问题是收集到的 json 没有在 Node.JS 中解析它显示以下错误
SyntaxError: Unexpected token / in JSON at position 0
代码片段如下
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
}
我尝试了以下方法来摆脱这种情况,但没有运气。
- 修剪输出,例如output.trim()
- 从 here 中删除了不可见的控制字符代码
- 删除了从 here 中提取的其他尾随或前导字符代码
- 尝试使用子字符串不考虑位置 0 处的第一个字符,然后错误更改,例如位置 0 处的无效标记 v
请帮助,这很令人沮丧
解决方法
基本上我无法成功删除导致错误的不可见控制字符,因此从 here 采取的下一个方法,这个已接受的答案没有显示删除,而是另一种提取实际 json 的方法来自垃圾字符串,然后解析 JSON 使其成为
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());
}