Tutorial

Como usar JSON.parse() e JSON.stringify()

Published on November 16, 2020
Default avatar

By Alligator.io

Português
Como usar JSON.parse() e JSON.stringify()

Introdução

O objeto JSON, disponível em todos os navegadores modernos, possui dois métodos úteis para lidar com o conteúdo formatado em JSON: parse e stringify. JSON.parse() recebe uma string JSON e a transforma em um objeto JavaScript. JSON.stringify() recebe um objeto JavaScript e o transforma em uma string JSON.

Vejamos um exemplo:

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"}

E, embora os métodos sejam geralmente usados em objetos, eles também podem ser usados em arrays:

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() pode receber uma função como um segundo argumento que transforma os valores do objeto antes de serem retornados. Aqui, os valores do objeto são transformados em maiúsculas no objeto retornado do método 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;
});

Nota: as vírgulas ao final não são válidas em JSON, então JSON.parse() gera um erro se a string passada para ele tiver vírgulas ao final.

JSON.stringify()

JSON.stringify() pode receber dois argumentos adicionais, sendo o primeiro uma função replacer e o segundo um valor String ou Number a ser usado como um space na string retornada.

A função replacer pode ser usada para filtrar valores, pois qualquer valor retornado como undefined estará fora da string retornada:

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"}"

E um exemplo com um argumento passado como space:

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

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

Conclusão

Neste tutorial, você aprendeu a como usar os métodos JSON.parse() e JSON.stringify(). Se você gostaria de aprender mais sobre como trabalhar com JSON no Javascript, confira nosso tutorial Como trabalhar com JSON no JavaScript.

Para mais informações sobre a programação em JavaScript, dê uma olhada em nossa série Como programar em JavaScript ou confira nossa página do tópico JavaScript para exercícios e projetos de programação.

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