如何解析未转义的单引号'从javascript谷歌翻译中的json字符串 [英] How to parse out unescaped single quote ' from json string in javascript Google Translate
问题描述
我正在打电话给Google翻译api并获取未完全解码的字符串.特别是,我看到的是'应该在单引号所在的位置.
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.
例如:
{
"q": "det är fullt",
"target": "en"
}
返回
{
"data": {
"translations": [
{
"translatedText": "It&\#39;s full",
"detectedSourceLanguage": "sv"
}
]
}
}
我本来希望JSON.parse能够解决这个问题,但事实并非如此.我还需要调用其他一些本机函数吗?我目前的解决方法是使用正则表达式 .replace(/'/g,'");
来解决此问题,但是有没有更好的方法使用javascript来解码这种类型的东西?
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?
推荐答案
啊!造成此问题的原因是响应是HTML编码的.
Aha! The issue is caused because the response is HTML encoded.
如果我直接将翻译内容放到页面上,引号就可以了.但是,我将结果放在文本区域中,以使用户有机会编辑该翻译.结果,浏览器不会自动将字符串作为HTML读取,因为它不会直接呈现为HTML.
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.
我现在使用的解决方案是使用DOMParser解码字符串,如对此所述stackoverflow线程:
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);
这篇关于如何解析未转义的单引号&#39;从javascript谷歌翻译中的json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!