JavaScript Fundamentals -- Objects in JavaScript

Stringify-ing Objects and Parsing Objects


When you're debugging your application that you need to print an object to the console so you can see what information was in the object at a given time. The JSON class's stringify method is perfect for doing this. It prints the object out as a string instead of as a real object:

const pizza = {
    name: 'Pepperoni',
    price: 8,
    toppings: ['marinara', 'cheese', 'pepperoni']

console.log(JSON.stringify(pizza)); // {"name":"Pepperoni","price":8,"toppings":["marinara","cheese","pepperoni"]}

If you want the object to print out with indentation instead of on one line, you call the function like this:

console.log(JSON.stringify(pizza, null, 2)); 

/* Console:

Finally, if you want to remove any information from the printed string (for example, sensitive information), you can pass in an array of strings. The array that's passed in should include the strings you want to keep in the printed object:

console.log(JSON.stringify(pizza, ['name', 'price'], 2)); 

/* Console:

To convert a string to an object, you can do the following:

const pizzaString = JSON.stringify(pizza); 
const newPizzaObject = JSON.parse(pizzaString);

Now the newPizzaObject will look just like the original pizza. Be careful though to only pass in the string representation of an object or array to the parse method. Otherwise a Syntax Error will occur.

Read this blog post for more information.


I finished! On to the next chapter