[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/JSON [Back]  [Original]

JSON - JavaScript | MDN

Esta pgina ha sido traducida del ingls por la comunidad. Aprende ms y nete a la comunidad de MDN Web Docs.

View in English Always switch to English

JSON

Baseline Widely available *

This feature is well established and works across many devices and browser versions. Its been available across browsers since julio de 2015.

* Some parts of this feature may have varying levels of support.

Resumen

El objeto JSON contiene mtodos para analizar JavaScript Object Notation (JSON) y convertir valores a JSON. No puede ser llamado o construdo, y aparte de estas dos propiedades, no tiene funcionalidad interesante por s mismo.

In this article

Descripcin

JavaScript Object Notation

JSON es una sintaxis para serializar objetos, arreglos, nmeros, cadenas, booleanos y nulos. Est basado sobre sintaxis JavaScript pero es diferente a ella: algo JavaScript no es JSON, y algo JSON no es JavaScript. Mira tambin: JSON: The JavaScript subset that isn't.

Tipo JavaScript Diferencia JSON
Objetos y arreglos Los nombres de las propiedades deben tener doble comilla; las comas finales estn prohibidas.
Nmeros Los ceros a la izquierda estn prohibidos; un punto decimal debe ser seguido al menos por un dgito.
Cadenas Solo un limitado conjunto de caracteres pueden ser de escape; ciertos caracteres de control estan prohibidos; los caracteres de separador de linea Unicode (U+2028) y el separador de parrafo (U+2029) son permitidos; las cadenas deben estar entre comillas dobles. Mira el siguiente ejemplo donde JSON.parse funciona bien y unSyntaxError es generado cuando se evalua el codigo como JavaScript:
var code = '"\u2028\u2029"';
JSON.parse(code); // works fine
eval(code); // fails

La sintaxis JSON completa es la siguiente:

js
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

Espacios en blanco insignificantes pueden estar presentes en cualquier lugar excepto en un JSONNumber (los nmeros no deben contener ningn espacio) o en una JSONString (donde es interpretado como el caracter correspondiente en la cadena, o podra causar un error). Los caracteres de Tabulacin (U+0009), de retorno de carro (U+000D), de nueva lnea (U+000A), y de espacio (U+0020) son los nicos caracteres de espacios en blanco vlidos.

Mtodos

JSON.parse()

Analiza una cadena de texto JSON, opcionalmente transformando el valor producido y sus propiedades, retornando el valor.

JSON.stringify()

Devuelve un string JSON correspondiente al valor especificado, incluyendo opcionalmente ciertas propiedades o reemplazando valores de propiedades de la manera definida por el usuario.

Polyfill

El objeto JSON no es soportado por navegadores antiguos. Se puede solucionar esto insertando el siguiente cdigo al inicio del script, permitiendo usar el objeto JSON en navegadores que no soportan su implementacin de forma nativa (por ejemplo en Internet Explorer 6).

El siguiente algoritmo es una imitacin del objeto JSON nativo:

js
if (!window.JSON) {
  window.JSON = {
    parse: function (sJSON) {
      return eval("(" + sJSON + ")");
    },
    stringify: function (vContent) {
      if (vContent instanceof Object) {
        var sOutput = "";
        if (vContent.constructor === Array) {
          for (
            var nId = 0;
            nId < vContent.length;
            sOutput += this.stringify(vContent[nId]) + ",", nId++
          );
          return "[" + sOutput.substr(0, sOutput.length - 1) + "]";
        }
        if (vContent.toString !== Object.prototype.toString) {
          return '"' + vContent.toString().replace(/"/g, "\\$&") + '"';
        }
        for (var sProp in vContent) {
          sOutput +=
            '"' +
            sProp.replace(/"/g, "\\$&") +
            '":' +
            this.stringify(vContent[sProp]) +
            ",";
        }
        return "{" + sOutput.substr(0, sOutput.length - 1) + "}";
      }
      return typeof vContent === "string"
        ? '"' + vContent.replace(/"/g, "\\$&") + '"'
        : String(vContent);
    },
  };
}

Los objectos JSON2 y JSON3 son mas complejos que el objeto JSON ya que manejan polyfills.

Especificaciones

Specification
ECMAScript 2027 LanguageSpecification
# sec-json-object

Compatibilidad con navegadores

Vea tambin


Web Proxy Viewer  |  New URL  |  Original Page