Movatterモバイル変換


[0]ホーム

URL:


  1. Tecnología web para desarrolladores
  2. JavaScript
  3. Referencia de JavaScript
  4. Objetos globales
  5. JSON

Esta página ha sido traducida del inglés por la comunidad.Aprende más y únete a la comunidad de MDN Web Docs.

View in EnglishAlways switch to English

JSON

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨julio de 2015⁩.

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

Resumen

El objeto JSON contiene métodos para analizarJavaScript Object Notation (JSON) y convertir valores a JSON. No puede ser llamado o construído, y aparte de estas dos propiedades, no tiene funcionalidad interesante por sí mismo.

Descripción

JavaScript Object Notation

JSON es una sintaxis para serializar objetos, arreglos, números, 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 también:JSON: The JavaScript subset that isn't.

Tipo JavaScriptDiferencia JSON
Objetos y arreglosLos nombres de las propiedades deben tener doble comilla; las comas finales están prohibidas.
NúmerosLos ceros a la izquierda están prohibidos; un punto decimal debe ser seguido al menos por un dígito.
CadenasSolo 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 dondeJSON.parse funciona bien y unSyntaxError es generado cuando se evalua el codigo como #"js">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 JSONArrayJSONNumber = - PositiveNumber          or PositiveNumberPositiveNumber = DecimalNumber              or DecimalNumber . Digits              or DecimalNumber . Digits ExponentPart              or DecimalNumber ExponentPartDecimalNumber = 0              or OneToNine DigitsExponentPart = e Exponent            or E ExponentExponent = Digits        or + Digits        or - DigitsDigits = Digit      or Digits DigitDigit = 0 through 9OneToNine = 1 through 9JSONString = ""          or " StringCharacters "StringCharacters = StringCharacter                or StringCharacters StringCharacterStringCharacter = any character                  except " or \ or U+0000 through U+001F                or EscapeSequenceEscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t              or \u HexDigit HexDigit HexDigit HexDigitHexDigit = 0 through 9        or A through F        or a through fJSONObject = { }          or { Members }Members = JSONString : JSON        or Members , JSONString : JSONJSONArray = [ ]          or [ ArrayElements ]ArrayElements = JSON              or ArrayElements , JSON

Espacios en blanco insignificantes pueden estar presentes en cualquier lugar excepto en unJSONNumber (los números no deben contener ningún espacio) o en unaJSONString (donde es interpretado como el caracter correspondiente en la cadena, o podría causar un error). Los caracteres de Tabulación (U+0009), de retorno de carro (U+000D), de nueva línea (U+000A), y de espacio (U+0020) son los únicos caracteres de espacios en blanco válidos.

Métodos

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 código al inicio del script, permitiendo usar el objeto JSON en navegadores que no soportan su implementación de forma nativa (por ejemplo en Internet Explorer 6).

El siguiente algoritmo es una imitación 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 objectosJSON2 yJSON3 son mas complejos que el objeto JSON ya que manejanpolyfills.

Especificaciones

Specification
ECMAScript® 2026 Language Specification
# sec-json-object

Compatibilidad con navegadores

Vea también

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp