| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/JSON | [Back] [Original] |
Get to know MDN better
Esta pgina foi traduzida do ingls pela comunidade. Saiba mais e junte-se comunidade MDN Web Docs.
This feature is well established and works across many devices and browser versions. Its been available across browsers since julho de 2015.
* Some parts of this feature may have varying levels of support.
O Objeto JSON contm mtodos para parsing JavaScript Object Notation (JSON) e converso de valores para JSON. Ele no pode ser chamado ou construdo e, alm de suas propriedades de dois mtodos, ele no possui uma funcionalidade interessante.
JSON uma sintaxe para serializao de objetos, matrizes, nmeros, strings, booleanos, e null. Baseia-se em sintaxe Javascript, mas distinta desta: alguns Javascript no so JSON, e alguns JSON no so Javascript.
| JavaScript tipo | JSON diferenas |
|---|---|
| Objetos e Arrays | Os nomes das propriedades devem ser strings com aspas duplas; as vrgulas direita so proibidas. |
| Nmeros | Zeros esquerda so proibidos; um ponto decimal deve ser seguido por pelo menos um dgito. |
| Strings | Apenas um conjunto limitado de caracteres pode ser escapado; certos caracteres de controle so proibidos; o separador de linha Unicode (U+2028) e o separador de pargrafo (U+2029) caracteres so permitidos; strings devem ter aspas duplas.Veja o exemplo a seguir, onde JSON.parse() funciona bem e um SyntaxError lanado ao avaliar o cdigo como JavaScript: var code = '"\u2028\u2029"'; JSON.parse(code); // works fine eval(code); // fails |
A sintaxe completa do JSON a seguinte:
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
Espaos em branco podem estar presentes em qualquer lugar, exceto dentro de um JSONNumber (nmeros no devem conter espao em branco) ou JSONString (onde ele interpretado como o caractere correspondente na string, ou causaria um erro). O caractere de tabulao (U+0009), retorno de carro (U+000D), retorno de linha (U+000A), e espao (U+0020) so os nicos caracteres em branco vlidos.
JSON.parse()Analisar uma seqncia como JSON, opcionalmente transformar o valor produzido e suas propriedades, e retornar o valor.
JSON.stringify()Retorna uma string JSON correspondente ao valor especificado, opcionalmente, pode incluir apenas determinados propriedades ou substituir valores de propriedade de acordo com a definio feita pelo usurio.
O objeto JSON no suportado em navegadores mais antigos. Voc pode contornar este problema inserindo o seguinte cdigo no incio de seus scripts, permitindo o uso de JSON e navegadores sem suporte (como Internet Explorer 6).
O algoritmo a seguir uma imitao do objeto nativo JSON:
if (!window.JSON) {
window.JSON = {
parse: function (sJSON) {
return eval("(" + sJSON + ")");
},
stringify: (function () {
var toString = Object.prototype.toString;
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) {
if (value.hasOwnProperty(k))
tmp.push(stringify(k) + ": " + stringify(value[k]));
}
return "{" + tmp.join(", ") + "}";
}
}
return '"' + value.toString().replace(escRE, escFunc) + '"';
};
})(),
};
}
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-json-object |
This page was last modified on 17 de jun. de 2024 by MDN contributors.
Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |