How to decode Google Translate API responses correctly?

I communicate with the Google Translate API. I can send my request and get a response. The only problem is that some special characters are encoded. For instance:

" Clock " (EN) will be transferred to " L'horloge " (FR)

The API will send me this text L\u0026#39;horloge. How to convert such cases to unicode string?

+3
source share
2 answers

This is unicode JSON and HTML encoding.

JSON: http://code.google.com/p/superobject/source/browse/#svn/trunk

uses msxml, HTTPapp, superobject;
var
  xml: IXMLHTTPRequest;
begin
  xml := CoXMLHTTP.Create;
  xml.open('GET', 'http://www.googleapis.com/language/translate/v2?  key=YOURAPIKEYHERE&q=The%20clock&source=en&target=fr', False, EmptyParam, EmptyParam);
  xml.send('');
  Caption := HTMLDecode(SO(xml.responseText)  ['data.translations[0].translatedText'].AsString);
end;
+4

, :

function unescapeUTF8EscapeSeq($str) {
    return preg_replace_callback("/\\\u([0-9a-f]{4})/i",
        create_function('$matches',
            'return html_entity_decode(\'&#x\'.$matches[1].\';\', ENT_QUOTES, \'UTF-8\');'
        ), $str);
}

,

+2

Source: https://habr.com/ru/post/1773010/


All Articles