JavaScript JSON stringify() Metodo
Esempio
Stringi un oggetto JavaScript:
var obj = { "name":"John", "age":30, "city":"New York"};
var myJSON =
JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Altri esempi "Provalo da solo" di seguito.
Definizione e utilizzo
Il metodo JSON.stringify() converte gli oggetti JavaScript in stringhe.
Quando si inviano dati a un server web, i dati devono essere una stringa.
Supporto browser
I numeri nella tabella specificano la prima versione del browser che supporta completamente il metodo.
Method | |||||
---|---|---|---|---|---|
stringify() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Sintassi
JSON.stringify(obj, replacer, space)
Valori dei parametri
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. |
Dettagli tecnici
Valore di ritorno: | Una stringa |
---|---|
Versione JavaScript: | ECMAScript 5 |
Altri esempi
Esempio
Utilizzando la funzione di sostituzione :
/*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;
}
});
Esempio
Usando il parametro spazio :
/*Insert
10 space characters for each white space:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj,
null, 10);
Esempio
Usando il parametro spazio :
/*Insert
the word SPACE for each white space:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj,
null, "SPACE");
Pagine correlate
Esercitazione JSON: Introduzione a JSON