Características JSON en JavaScript

JSON en JavaScript
JSON en JavaScript

El objeto JSON en javascript contiene funciones que interpretan la sintaxis de notación de objetos de JavaScript (JSON) y convierten los valores en sintaxis JSON. Este objeto no está destinado a ser inicializado o construido (a través de un operador new), y no tiene trabajo propio excepto por tener dos funciones secundarias.

Características generales

La sintaxis JSON es una sintaxis para almacenar objetos, matrices, números, cadenas, valores booleanos y valores null. Se basa en la sintaxis de JavaScript pero difiere de ella, algunos códigos JavaScript no son válidos en JSON y algunos códigos JSON no son válidos en JavaScript. La siguiente tabla muestra algunas de las diferencias entre JavaScript y JSON cuando se trata de tipos de datos:

Tipo de datos en JavaScriptDiferencia en JSON
Objetos y matricesLos nombres de propiedad deben ir entre comillas dobles y no se permite una coma después del último elemento.
preparaciónLos ceros iniciales no están permitidos para números enteros (los ceros se ignorarán en una función JSON.stringify, pero la función JSON.parse arrojará el error SyntaxError). El punto decimal debe ir seguido de al menos un dígito.
cadenas de textoSolo se permite un subconjunto de los caracteres de escape, algunos caracteres de control no están permitidos y las cadenas de texto deben ir entre comillas dobles. Vea el siguiente ejemplo en el que la función funciona JSON.parse sin problemas pero arrojará un error SyntaxError al intentar interpretar la cadena como:

código JavaScript: var code = ‘»\u2028\u2029″‘; JSON.parse(code); // // funciona sin problemas eval ( código ); // fallar

Esta es la sintaxis JSON completa:

JSON = null
    or true or false
    or JSONNumber
    or JSONString
    or JSONObject
    or JSONArray

JSONNumber = - PositiveNumber
          or PositiveNumber
PositiveNumber = DecimalNumber
              or DecimalNumber . Digits
              or DecimalNumber . Digits ExponentPart
              or DecimalNumber ExponentPart
DecimalNumber = 0
             or OneToNine Digits
ExponentPart = e Exponent
            or E Exponent
Exponent = Digits
        or + Digits
        or - Digits
Digits = Digit
      or Digits Digit
Digit = 0 through 9
OneToNine = 1 through 9

JSONString = ""
          or " StringCharacters "
StringCharacters = StringCharacter
                or StringCharacters StringCharacter
StringCharacter = any character
                  except " or \ or U+0000 through U+001F
               or EscapeSequence
EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
              or \u HexDigit HexDigit HexDigit HexDigit
HexDigit = 0 through 9
        or A through F
        or a through f

JSONObject = { }
          or { Members }
Members = JSONString : JSON
       or Members , JSONString : JSON

JSONArray = [ ]
         or [ ArrayElements ]
ArrayElements = JSON
             or ArrayElements , JSON

Funciones JSON

JSON.parse()‎

Intérprete una cadena JSON, convierte opcionalmente el valor y los atributos y devuelva el resultado.

JSON.stringify()

Devuelve una cadena JSON asociada con el valor dado y, opcionalmente, se puede hacer que contenga propiedades específicas o reemplazar valores de propiedad según lo desee el usuario.

Falta de compatibilidad con el navegador

El objeto JSON no era compatible con navegadores más antiguos. Este problema puede evitarse agregando el siguiente código al comienzo de los scripts, lo que permite que el objeto se utiliza JSON en navegadores que no lo admitan (por ejemplo, versiones anteriores de IE).

El siguiente algoritmo simula el objeto JSON:

if (!window.JSON) {
  window.JSON = {
    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
    stringify: (function () {
      var toString = Object.prototype.toString;
      var hasOwnProperty = Object.prototype.hasOwnProperty;
      var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
      var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
      var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
      var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
      return function stringify(value) {
        if (value == null) {
          return 'null';
        } else if (typeof value === 'number') {
          return isFinite(value) ? value.toString() : 'null';
        } else if (typeof value === 'boolean') {
          return value.toString();
        } else if (typeof value === 'object') {
          if (typeof value.toJSON === 'function') {
            return stringify(value.toJSON());
          } else if (isArray(value)) {
            var res = '[';
            for (var i = 0; i < value.length; i++)
              res += (i ? ', ' : '') + stringify(value[i]);
            return res + ']';
          } else if (toString.call(value) === '[object Object]') {
            var tmp = [];
            for (var k in value) {
              // in case "hasOwnProperty" has been shadowed
              if (hasOwnProperty.call(value, k))
                tmp.push(stringify(k) + ': ' + stringify(value[k]));
            }
            return '{' + tmp.join(', ') + '}';
          }
        }
        return '"' + value.toString().replace(escRE, escFunc) + '"';
      };
    })()
  };
}

Para obtener soluciones más complejas para agregar compatibilidad con un objeto JSON, consulte JSON2 y JSON3.

Soporte de navegadores

CaracterísticaChromeFirefoxIEOperaSafari
Soporte básico3,5810,54