Fetch Response.json错误的转义字符

1 人关注

所以,本质上我有一个fetch,接触到一个API,然后得到一个JSON对象作为回应。问题是,API会给单引号加上一个转义字符,例如 isn\'t 。这在JSON.parse()中引发了一个错误,所以我想在调用response.json()之前对响应的主体进行操作。所以这是我目前的代码。

    httpCallout(){
    fetch('/1.0/?method=getQuote&lang=en&format=json', {method: "GET", cache: "no-cache"})
    .then(response => {
      return response.json()
    .then((data) => {
      const quote = data.quoteText;
      this.setState({
        quote: quote,
        author: data.quoteAuthor
    this.colorChange(rgb);

问题是,每当调用response.json ,都有一个转义的单引号。我知道我可以抓住这个错误,什么都不做,但我更希望有一个解决方案,可以让我解析出转义的单引号,并且仍然可以从这个调用中设置我的状态。

从本质上讲,我想做的是,在运行response.json()之前,将一个带有类似于"It\'s tiring isn\'t it?" 的quoteText值的响应正确解析为"It's tiring isn't it?" ,这样就不会出现Bad escape character 的错误。

8 个评论
该JSON字符串没有任何问题
这就是我感到困惑的原因。当我通过Postman GET时,我没有得到错误。只有当我试图通过response.json()或JSON.parse(response.body)来解析JSON时才会出现错误。
你不能在你的承诺流中添加一个 .catch(err => console.error(err)) ,看看发生了什么事吗?
应该把你从服务器上收到的确切字符串作为问题的一部分,以便我们能够查看。
@balexandre 我也有这样的错误,在转义的单引号上出现了JSON坏字符错误。在我弄清楚发生了什么之后,我去掉了捕捉块。
@msbit 这是一个随机选择的引号字符串。大多数字符串工作得很好,唯一的问题是每当我收到一个字符串,其中有一个单引号,因为服务器返回一个转义的单引号 \' ,每当我试图解析JSON时,我得到一个错误的转义字符。
@Pointy Btw 在测试了带有转义单引号的字符串后,似乎它们不被接受为有效的JSON字符串。
啊,是的,我明白了。我猜你是从 forismatic.com/en/api 获取的。用下面的方法。 {"quoteText":"You can\'t shake hands with a clenched fist.", "quoteAuthor":"Indira Gandhi", "senderName":"", "senderLink":"", "quoteLink":"http://forismatic.com/en/72b4eb8861/"} ,我得到 Uncaught (in promise) SyntaxError: JSON.parse: bad escaped character at line 1 column 23 of the JSON data 。一个答案是向API的管理员提交一份错误报告,因为它返回了畸形的响应。
javascript
json
http
fetch
jacksons123
jacksons123
发布于 2021-04-30
1 个回答
msbit
msbit
发布于 2021-04-30
已采纳
0 人赞同

如果你无法让数据提供者清理他们的数据库或JSON编码管道,你可以通过以下方式手动清理返回的文本。

  • Response 转换为文本,使用 Body.text() (而不是 Body.json() )
  • 用(而不是)替换掉违规的部分 String.replaceAll()
  • 明确地解析JSON,用 JSON.parse()
  • 在你的函数中把这些放在一起,我们有。

    function httpCallout () {
      fetch('/1.0/?method=getQuote&lang=en&format=json', { method: 'GET', cache: 'no-cache' })
        .then(response => response.text())
        .then(text => {
          const cleanText = text.replaceAll("\\'", "'");
          return JSON.parse(cleanText);
        .then(data => {
          const quote = data.quoteText;
          this.setState({
            quote: quote,
            author: data.quoteAuthor