Méthode JavaScript JSON stringify()
Exemple
Stringifiez un objet JavaScript :
var obj = { "name":"John", "age":30, "city":"New York"};
var myJSON =
JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Plus d'exemples "Essayez-le vous-même" ci-dessous.
Définition et utilisation
La méthode JSON.stringify() convertit les objets JavaScript en chaînes.
Lors de l'envoi de données à un serveur Web, les données doivent être une chaîne.
Prise en charge du navigateur
Les nombres dans le tableau indiquent la première version du navigateur qui prend entièrement en charge la méthode.
Method | |||||
---|---|---|---|---|---|
stringify() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Syntaxe
JSON.stringify(obj, replacer, space)
Valeurs des paramètres
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. |
Détails techniques
Valeur de retour : | Un string |
---|---|
Version JavaScript : | ECMAScript 5 |
Plus d'exemples
Exemple
Utilisation de la fonction de remplacement :
/*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;
}
});
Exemple
Utilisation du paramètre espace :
/*Insert
10 space characters for each white space:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj,
null, 10);
Exemple
Utilisation du paramètre espace :
/*Insert
the word SPACE for each white space:*/
var obj = { "name":"John",
"age":"39", "city":"New York"};
var text = JSON.stringify(obj,
null, "SPACE");
Pages connexes
Tutoriel JSON : Présentation de JSON