Método JavaScript JSON stringify()
Exemplo
Stringify um objeto JavaScript:
var obj = { "name":"John", "age":30, "city":"New York"};
var myJSON =
JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Mais exemplos de "Experimente você mesmo" abaixo.
Definição e uso
O método JSON.stringify() converte objetos JavaScript em strings.
Ao enviar dados para um servidor web, os dados devem ser uma string.
Suporte ao navegador
Os números na tabela especificam a primeira versão do navegador que oferece suporte total ao método.
Method | |||||
---|---|---|---|---|---|
stringify() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Sintaxe
JSON.stringify(obj, replacer, space)
Valores de parâmetro
Parameter | Description |
---|---|
obj | Required. The value to convert to a string |
replacer | Optional. Either a function or an array used to transform the result. The replacer is called for each item. |
space | Optional. Either a String or a Number. A string to be used as white space (max 10 characters), or a Number, from 0 to 10, to indicate how many space characters to use as white space. |
Detalhes técnicos
Valor de retorno: | Uma linha |
---|---|
Versão JavaScript: | ECMAScript 5 |
Mais exemplos
Exemplo
Usando a função de substituição :
/*replace the value of "city" to upper case:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj, function
(key, value) {
if (key == "city") {
return value.toUpperCase();
} else {
return value;
}
});
Exemplo
Usando o parâmetro espaço :
/*Insert
10 space characters for each white space:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj,
null, 10);
Exemplo
Usando o parâmetro espaço :
/*Insert
the word SPACE for each white space:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj,
null, "SPACE");
Páginas relacionadas
Tutorial JSON: Introdução ao JSON