Strict but slow to convert String to Json - Node.js String

Node.js examples for String:Convert

Description

Strict but slow to convert String to Json

Demo Code

String.prototype.toJSON = function(){
  var tmp = this.split("");
  for(var i=0;i<tmp.length;i++){
    var c = tmp[i];
    (c >= ' ') ?
      (c == '\\') ? (tmp[i] = '\\\\'):
      (c == '"')  ? (tmp[i] = '\\"' ): 0 :
    (tmp[i] = // w  w  w . ja  va 2 s .  c o m
      (c == '\n') ? '\\n' :
      (c == '\r') ? '\\r' :
      (c == '\t') ? '\\t' :
      (c == '\b') ? '\\b' :
      (c == '\f') ? '\\f' :
      (c = c.charCodeAt(),('\\u00' + ((c>15)?1:0)+(c%16)))
    )
  }
  return '"' + tmp.join("") + '"';
}

Related Tutorials