How to parse out unescaped single quote ' from json string in javascript Google Translate

為{幸葍}努か 提交于 2021-01-27 19:13:31

问题


I am calling google translate api and getting back strings that are not fully decoded. In particular, I am seeing ' where single quotes should be.

For example:

{
  "q": "det är fullt",
  "target": "en"
}

Returns

{
   "data": {
      "translations": [
       {
        "translatedText": "It&\#39;s full",
        "detectedSourceLanguage": "sv"
      }
    ]
  }
}

I would have expected JSON.parse to take care of this, but it does not. Is there some other native function I need to be calling? My current fix is to fix this using a regex .replace(/'/g, "'");, but is there a better way to decode this type of thing using javascript?


回答1:


Aha! The issue is caused because the response is HTML encoded.

If I were to put the translation onto the page directly, the quote renders just fine. However, I am putting the result in a textarea to give users a chance to edit that translation. As a result, the browser is not automatically reading the string as HTML since it is not rendered directly as HTML.

The solution I am now using is to decode the string using DOMParser as described on this stackoverflow thread:

var encodedStr = 'hello & world';

var parser = new DOMParser;
var dom = parser.parseFromString(
    '<!doctype html><body>' + encodedStr,
    'text/html');
var decodedString = dom.body.textContent;

console.log(decodedString);


来源:https://stackoverflow.com/questions/44548734/how-to-parse-out-unescaped-single-quote-39-from-json-string-in-javascript-goo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!