【问题标题】:Can't parse JSON because of trailing whitespaces in JSON String由于 JSON 字符串中的尾随空格而无法解析 JSON
【发布时间】:2020-01-25 03:51:40
【问题描述】:

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

我通过修剪每个值来尝试恢复器,但它仍然不起作用。

这是我收到语法错误的 JSON 字符串的 sn-p:

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

这是我得到的错误:

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

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

【问题讨论】:

  • without string manipulation? 嗯?您将 必须 操作字符串 以某种方式 以更改它以使其可解析,这是什么意思?

标签: node.js json parsing


【解决方案1】:

格式正确的 JSON 字符串不得包含任何文字换行符 - 它只能包含换行符的表示,例如\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);

【讨论】:

  • 又一个例子是 JSON 被过度用于“人工可编辑”的配置文件。
  • 谢谢,它对我有用
猜你喜欢
  • 2016-12-17
  • 2018-05-26
  • 1970-01-01
  • 2013-05-10
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 2017-09-01
  • 1970-01-01
相关资源
最近更新 更多