На рассмотрении

JSON.Stringify unexpected behaviour

Dan 4 месяца назад в Bugs and problems обновлен Vladimir Ovchinnikov 4 месяца назад 1

I am wanting to save a strinfigied table to tags, with some of the values containing line breaks.

To test, I am running the following code:

var tbl = {};
tbl.a = "ABC\r\n123"
tbl.b = "ABC\\r\\n123"

This gives the output in emulator:

[04-07-2019 11:06:06.412] INFO SCRIPT {"a":"ABC
123", "b":"ABC\\r\\n123"}

As JSON.stringify should automatically escape slash characters, I am expecting to get the following output:

[04-07-2019 11:06:06.412] INFO SCRIPT {"a":"ABC\r\n123", "b":"ABC\\r\\n123"}

This results in an error when I try to run JSON.Parse on the result. You can test this by running

var tbl = {};
tbl.a = "ABC\r\n123"
tbl.b = "ABC\\r\\n123"
var str = JSON.Stringify(tbl);

var tbl2 = JSON.Parse(str);

The above code should just duplicate the value stored in tbl to tbl2. When run, I get the error:

[04-07-2019 11:08:59.657] WARNING SCRIPT Script exception: SyntaxError: C:\Users\Dan Work\Documents\iRidium pro documents\Client\Project 1\scripts\Newscript.js:5: line 1: String literal not closed at end of line

For now I have implemented a workaround by creating a new stringify function that replaces the CR and LF after the fact, and always calling this one instead

function newStringify(tbl) {
    var str = JSON.Stringify(tbl);
    str = str.replace(/\r/g, "\\r").replace(/\n/g, "\\n");
    return str;

На рассмотрении


Error because invalid characters are used in JSON.

Сервис поддержки клиентов работает на платформе UserEcho