Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify and "\u2028\u2029" check?

Sometimes I see in a view source page ( html view source) this code:

if (JSON.stringify(["\u2028\u2029"]) === '["\u2028\u2029"]') JSON.stringify = function (a) {
    var b = /\u2028/g,
        c = /\u2029/g;
    return function (d, e, f) {
        var g = a.call(this, d, e, f);
        if (g) {
            if (-1 < g.indexOf('\u2028')) g = g.replace(b, '\\u2028');
            if (-1 < g.indexOf('\u2029')) g = g.replace(c, '\\u2029');
        }
        return g;
    };
}(JSON.stringify);
  • What is the problem with JSON.stringify(["\u2028\u2029"]) that it needs to be checked ?

Additional info :

  • JSON.stringify(["\u2028\u2029"]) value is "["

"]"
  • '["\u2028\u2029"]' value is also "["

"]"
like image 532
Royi Namir Avatar asked May 22 '13 08:05

Royi Namir


1 Answers

After reading both answers , here is the Simple visual explanation :

doing this

alert(JSON.stringify({"a":"sddd\u2028sssss"})) // can cause problems

will alert :

enter image description here

While changing the trouble maker to something else ( for example from \u to \1u)

will alert :

enter image description here

Now , let's invoke the function from my original Q ,

Lets try this alert(JSON.stringify({"a":"sddd\u2028sssss"})) again :

result :

enter image description here

and now , everybody's happy.

like image 110
Royi Namir Avatar answered Oct 31 '22 10:10

Royi Namir