Une utilisation courante de JSON consiste à échanger des données vers/depuis un serveur Web.
Lors de l'envoi de données à un serveur Web, les données doivent être un string.
Convertissez un objet JavaScript en chaîne avec JSON.stringify().
Imaginez que nous ayons cet objet en JavaScript :
const obj = {name: "John", age: 30, city: "New York"};Utilisez la fonction JavaScript JSON.stringify() pour la convertir en chaîne.
const myJSON = JSON.stringify(obj);Le résultat sera une chaîne suivant la notation JSON.
myJSON est maintenant une chaîne, et prête à être envoyée à un serveur :
const obj = {name: "John", age: 30, city: "New York"};
const myJSON =
JSON.stringify(obj);
Essayez-le vous-même →
<!DOCTYPE html>
<html>
<body>
<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>
Vous apprendrez comment envoyer du JSON à un serveur dans les prochains chapitres.
Il est également possible de stringifier des tableaux JavaScript :
Imaginez que nous ayons ce tableau en JavaScript :
const arr = ["John", "Peter", "Sally", "Jane"];Utilisez la fonction JavaScript JSON.stringify() pour la convertir en chaîne.
const myJSON = JSON.stringify(arr);Le résultat sera une chaîne suivant la notation JSON.
myJSON est maintenant une chaîne, et prête à être envoyée à un serveur :
const arr = ["John", "Peter", "Sally", "Jane"];
const myJSON =
JSON.stringify(arr);
Essayez-le vous-même →
<!DOCTYPE html>
<html>
<body>
<h2>Create a JSON string from a JavaScript array.</h2>
<p id="demo"></p>
<script>
const arr = ["John", "Peter", "Sally", "Jane"];
const myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>
Vous apprendrez comment envoyer une chaîne JSON à un serveur dans les prochains chapitres.
Lors du stockage de données, celles-ci doivent être dans un certain format, et quel que soit l'endroit où vous choisissez de les stocker, Le texte est toujours l'un des formats légaux.
JSON permet de stocker des objets JavaScript sous forme de texte.
Stockage des données dans le stockage local
// Storing data:
const myObj = {name: "John",
age: 31, city: "New York"};
const myJSON =
JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
let text = localStorage.getItem("testJSON");
let obj =
JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;Essayez-le vous-même →
<!DOCTYPE html>
<html>
<body>
<h2>Store and retrieve data from local storage.</h2>
<p id="demo"></p>
<script>
// Storing data:
const myObj = { name: "John", age: 31, city: "New York" };
const myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
let text = localStorage.getItem("testJSON");
let obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
</script>
</body>
</html>
En JSON, les objets date ne sont pas autorisés. La fonction JSON.stringify() convertira toutes les dates en chaînes.
const obj = {name: "John", today: new Date(), city : "New York"};
const myJSON = JSON.stringify(obj);Essayez-le vous-même →
<!DOCTYPE html>
<html>
<body>
<h2>JSON.stringify() converts date objects into strings.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", today: new Date(), city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>
Vous pouvez reconvertir la chaîne en objet date chez le récepteur.
En JSON, les fonctions ne sont pas autorisées en tant que valeurs d'objet.
La fonction JSON.stringify() supprimera toutes les fonctions d'un JavaScript objet, à la fois la clé et la valeur :
const obj = {name: "John", age: function () {return 30;}, city: "New York"};
const myJSON = JSON.stringify(obj);Essayez-le vous-même →
<!DOCTYPE html>
<html>
<body>
<h2>JSON.stringify() will remove any functions from an object.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", age: function () {return 30;}, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>
Cela peut être omis si vous convertissez vos fonctions en chaînes avant d'exécuter la fonction JSON.stringify().
const obj = {name: "John", age: function () {return 30;}, city: "New York"};
obj.age = obj.age.toString();
const myJSON = JSON.stringify(obj);Essayez-le vous-même →
<!DOCTYPE html>
<html>
<body>
<h2>JSON.stringify() will remove any functions from an object.</h2>
<p>Convert functions into strings to keep them in the JSON object.</p>
<p id="demo"></p>
<script>
const obj = {name: "John", age: function () {return 30;}, city: "New York"};
obj.age = obj.age.toString();
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>
Si vous envoyez des fonctions en utilisant JSON, les fonctions perdront leur portée et le destinataire il faudrait utiliser eval() pour les reconvertir en fonctions.