Tutorial

Cómo usar JSON.parse() y JSON.stringify()

Published on November 16, 2020
Default avatar

By Alligator.io

Español
Cómo usar JSON.parse() y JSON.stringify()

Introducción

El objeto JSON, que está disponible en todos los navegadores modernos, tiene dos útiles métodos para manejar el contenido con formato JSON: parse y stringify. JSON.parse() toma una cadena JSON y la transforma en un objeto de JavaScript JSON.stringify() toma un objeto de JavaScript y lo transforma en una cadena JSON.

Aquí tiene un ejemplo:

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

A pesar de que los métodos se utilizan generalmente en objetos, también se pueden usar en matrices:

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() puede tomar una función como segundo argumento que puede transformar los valores de objeto antes de que se devuelvan. Aquí los valores del objeto se convierten en mayúsculas en el objeto devuelto del 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: Las comas al final no son válidas en JSON, por lo que JSON.parse() genera un error si la cadena que se pasa a ella tiene comas al final.

JSON.stringify()

JSON.stringify() puede tomar dos argumentos adicionales: el primero es una función replacer y el segundo es un valor String o Number que se utiliza como un space en la cadena que se devuelve.

La función de reemplazo se puede usar para filtrar los valores, ya que cualquier valor devuelto como undefined estará fuera de la cadena devuelta:

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

Y un ejemplo con un argumento space aprobado:

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

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

Conclusión

En este tutorial, se exploró cómo usar los métodos JSON.parse() y JSON.stringify(). Si desea obtener más información sobre cómo trabajar con JSON en Javascript, consulte nuestro tutorial Cómo trabajar con JSON en JavaScript.

Para obtener más información sobre la codificación en JavaScript, consulte nuestra serie Cómo codificar en JavaScript o consulte nuestra página sobre el tema JavaScript para ver ejercicios y proyectos de programación.

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