Tutorial

Comment utiliser JSON.parse() et JSON.stringify()

Published on November 16, 2020
Default avatar

By Alligator.io

Français
Comment utiliser JSON.parse() et JSON.stringify()

Introduction

L’objet JSON, disponible dans tous les navigateurs modernes, dispose de deux méthodes utiles pour traiter le contenu formaté en JSON : parse et stringify. JSON.parse() transforme une chaîne JSON en un objet JavaScript. JSON.stringify() transforme un objet JavaScript en une chaîne JSON.

Voici un exemple :

const myObj = {
  name: 'Skip',
  age: 2,
  favoriteFood: 'Steak'
};

const myObjStr = JSON.stringify(myObj);

console.log(myObjStr);
// "{"name":"Sammy","age":6,"favoriteFood":"Tofu"}"

console.log(JSON.parse(myObjStr));
// Object {name:"Sammy",age:6,favoriteFood:"Tofu"}

Et bien que les méthodes soient généralement utilisées sur des objets, elles peuvent également être utilisées sur des tableaux :

const myArr = ['bacon', 'lettuce', 'tomatoes'];

const myArrStr = JSON.stringify(myArr);

console.log(myArrStr);
// "["shark","fish","dolphin"]"

console.log(JSON.parse(myArrStr));
// ["shark","fish","dolphin"]

JSON.parse()

JSON.parse() peut prendre une fonction comme second argument, capable de transformer les valeurs de l’objet avant qu’elles ne soient renvoyées. Ici, les valeurs de l’objet sont transformées en majuscules dans l’objet renvoyé de la méthode parse :

const user = {
  name: 'Sammy',
  email: 'Sammy@domain.com',
  plan: 'Pro'
};

const userStr = JSON.stringify(user);

JSON.parse(userStr, (key, value) => {
  if (typeof value === 'string') {
    return value.toUpperCase();
  }
  return value;
});

Remarque : les virgules de fin de ligne ne sont pas valables dans JSON, donc JSON.parse() envoie un message d’erreur si la chaîne qui lui est passée comporte des virgules de fin de ligne.

JSON.stringify()

JSON.stringify() peut prendre deux arguments supplémentaires, le premier étant une fonction replacer et le second une valeur String ou Number à utiliser en tant que space dans la chaîne renvoyée.

La fonction replacer peut être utilisée pour filtrer les valeurs, car toute valeur renvoyée comme undefined sera exclue de la chaîne renvoyée :

const user = {
  id: 229,
  name: 'Sammy',
  email: 'Sammy@domain.com'
};

function replacer(key, value) {
  console.log(typeof value);
  if (key === 'email') {
    return undefined;
  }
  return value;
}

const userStr = JSON.stringify(user, replacer);
// "{"id":229,"name":"Sammy"}"

Et un exemple avec un argument space passé en revue :

const user = {
  name: 'Sammy',
  email: 'Sammy@domain.com',
  plan: 'Pro'
};

const userStr = JSON.stringify(user, null, '...');
// "{
// ..."name": "Sammy",
// ..."email": "Sammy@domain.com",
// ..."plan": "Pro"
// }"

Conclusion

Dans ce tutoriel, vous avez appris comment utiliser les méthodes JSON.parse() et JSON.stringify(). Si vous souhaitez en savoir plus sur le travail avec JSON en Javascript, consultez notre tutoriel Comment travailler avec JSON en JavaScript.

Pour plus d’informations sur le codage en JavaScript, consultez notre série Comment coder en JavaScript ou notre page thématique JavaScript d’exercices et de projets de programmation.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alligator.io

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel