Metoda stringify() JavaScriptu JSON
Příklad
Stringifikace objektu JavaScriptu:
var obj = { "name":"John", "age":30, "city":"New York"};
var myJSON =
JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Další příklady „Vyzkoušejte si to sami“ níže.
Definice a použití
Metoda JSON.stringify() převádí objekty JavaScriptu na řetězce.
Při odesílání dat na webový server musí být daty řetězec.
Podpora prohlížeče
Čísla v tabulce určují první verzi prohlížeče, která tuto metodu plně podporuje.
Method | |||||
---|---|---|---|---|---|
stringify() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Syntax
JSON.stringify(obj, replacer, space)
Hodnoty parametrů
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. |
Technické údaje
Návratová hodnota: | Řetězec |
---|---|
Verze JavaScriptu: | ECMAScript 5 |
Další příklady
Příklad
Použití funkce náhrady :
/*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;
}
});
Příklad
Pomocí parametru space :
/*Insert
10 space characters for each white space:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj,
null, 10);
Příklad
Pomocí parametru space :
/*Insert
the word SPACE for each white space:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj,
null, "SPACE");
Související stránky
Kurz JSON: Úvod do JSON