JSON Encoding

All functions of the JSON API expect and return UTF-8 strings. Therefore, the functions JsonParse, JsonSetStringProperty, and JsonArraySetStringElement expect the values in UTF-8 representation. Accordingly, the functions JsonToText, JsonGetStringProperty, and JsonArrayGetStringElement deliver the values in UTF-8 encoding.

To convert ANSI strings to UTF-8 strings and vice versa, you can use the functions ToUTF8 and FromUTF8.

If there are no special characters (for example ©, ¥, £, ä, ö, ü) in the text, all JSON API functions convert the ANSI string to an UTF-8 string implicitly. Otherwise an explicit conversion is required.

It is recommended to convert ANSI strings to UTF-8 strings in any case.

Encoding rules for all JSON API functions:

Input Output FromUTF8 (Output)
ToUTF8("CYL") CYL CYL
ToUTF8("©¥£") ©¥£ ©¥£
ToUTF8("©¥£") ©¥£ ©¥£
CYL CYL CYL
©¥£ ©¥£ Error: string conversion failed
©¥£ ©¥£ ©¥£
Note: TrueLog Explorer only displays JSON data in ANSI encoding correctly. Therefore, a call to the function FromUTF8 is necessary.

JsonParse decodes UTF-8 characters automatically.

Additional encoding rules for JsonParse:

Input Output FromUTF8 (Output)
ToUTF8( " \u00A9\u00A5\u00A3") ©¥£ ©¥£
\u00A9\u00A5\u00A3 ©¥£ ©¥£

You do not need to convert texts without special characters.

transaction TMain
var
  jsonText, jsonResult : string;
  jsonArray            : number;
begin
  jsonText := "[
                 \"CYL\",
                 \"©¥£\"
              ]";

  jsonArray := JsonParse(jsonText);
  JsonToText(jsonArray, jsonResult);

  Print(“UTF8: “ + jsonResult);                
  Print(“ANSI: “ + FromUTF8(jsonResult));     
  JsonFree(jsonArray);
End Tmain;

Output:

UTF8: [“CYL”,“©¥£”]
ANSI: [“CYL”,“©¥£”]

If a text contains a special character and you try to convert it to ANSI, an error occurs.

transaction TMain
var
  jsonText, jsonResult : string;
  jsonArray            : number;
begin
  jsonText := "[
                 \"CYL\",
                 \"©¥£\"
                 \"©¥£\"
              ]";

  jsonArray := JsonParse(jsonText);
  JsonToText(jsonArray, jsonResult);

  Print(“UTF8: “ + jsonResult);                
  Print(“ANSI: “ + FromUTF8(jsonResult));      

  JsonFree(jsonArray);
End Tmain;

Output:

UTF8: [“CYL”,“©¥£”,“©¥£”]
Error: String conversion failed

When the input text is converted to UTF-8, everything works as expected:

transaction TMain
var
  jsonText, jsonResult : string;
  jsonArray            : number;
begin
  jsonText := "[
                 \"CYL\",
                 \"©¥£\",
                 \"©¥£\"
              ]";

  jsonArray := JsonParse(jsonText);
  JsonToText(jsonArray, jsonResult);

  Print(“UTF8: “ + jsonResult);                
  Print(“ANSI: “ + FromUTF8(jsonResult));  
   
  JsonFree(jsonArray);
End Tmain;

Output:

UTF8: [“CYL”,“©¥£”,“ ©¥£”]
ANSI: [“CYL”,“©¥£”,“ ©¥£”]