由于JSON字符串中有空格,因此无法解析JSON

问题描述 投票:0回答:1

我目前正在使用网页抓取工具,并且正在从特定网页上的<script type="application/ld+json>获取JSON。我使用Cheerio将其作为字符串获取,并将其传递到JSON解析器(npm包)中。但是我继续收到语法错误,如果该值具有尾随空格,则会发生这种情况。

我通过调整每个值尝试了reviver,但仍然不起作用。

这是我的JSON字符串的片段,出现语法错误:

{"...821", "description":"                                                  \r\n
                                ","@type":"Organization",...}

这是我得到的错误:

ErrorEXError [JSONError]: Unexpected token       in JSON at position 1432 while parsing near '...821","description":"                                                \r\n                                             ","...'

如何在不进行字符串操作的情况下修整description值?

node.js json parsing
1个回答
0
投票

格式正确的JSON字符串不得包含任何文字换行符-它只能包含representations换行符,例如\r\n。用\n替换所有文字换行符,您应该可以正确解析它:

const jsonStr = `{"description":"                                                  \r\n
                                ","@type":"Organization"}`;
const jsonStrWithoutNewlines = jsonStr.replace(/[\n\r]+/g, '\\n');
const obj = JSON.parse(jsonStrWithoutNewlines);
console.log(obj);

也不允许使用制表符,如果有问题,请用\t替换它们:

const jsonStr = `{"description":"                                                  \r\n
                                ","@type":"Organization			"}`;
const jsonStrWithoutNewlines = jsonStr
  .replace(/[\n\r]+/g, '\\n')
  .replace(/\t/g, '\\t');
const obj = JSON.parse(jsonStrWithoutNewlines);
console.log(obj);
© www.soinside.com 2019 - 2024. All rights reserved.