Topic 3: JSON Parse, Stringify

JSON

JSON is a JavaScript data-storage format that can be used to exchange information between web services. In JSON notation, an object is formatted as a string. When written in JSON, property keys need to be in double quotes.Values can include strings in double quotes, numbers, booleans, null, arrays and objects. Methods are not allowed.

Here is an object that I will change to JSON string representation

JSON Stringify

The JSON stringify method will take a JavaScript object and turn it into a JSON string. Notice that the string doesn't have the message method in it. Because functions are not allowed, JSON.stringify skips over it.

// Javascript Object
let pizza = {
name: "Pizza",
foodGroup: "junk food",
yummy :true,
calories: 650,
toppings : ["Peperoni","Sausage","Cheese","Olives","Mushrooms"],
message: function() {return "Yummy in my tummy!";}
};

// stringify object JSON.stringify(pizza);

JSON Parse

The JSON parse method does the opposite of stringify. It will take a JSON string and turn it into a JavaScript Object. I have run the resulting object through a for in loop to display it's key-value pairs.

JSON string
let milkshake = '{"name":"Pizza","foodGroup":"junkfood","yummy":true,"calories":650,"toppings":["Peperoni","Sausage","Cheese","Olives","Mushrooms"]}

// parse string'
JSON.parse(milkshake);

reviver perameter

JSON.parse has an optional parameter called reviver. It allows you to add a function to check each of the parameters and possibly change the as they are parsed. You can add a function to change a date to UTC format, change a particular value, etc. You would need to add an if else statement to handle the other values that you don't want to change. If a value is null or undefined, it will be deleted.

Here is a object to be changed to a JSON string, and the code and the JSON.parse with a reviver parameter. Below you can see the results of the parse.

// object to be stringified
const numbers = {1: "1", 2: "2", 3: "3", 4: "4", 5: "5"};

// parse with reviver
let message = "";
const numbersReviver = JSON.parse(numbersString, function(key, value) {
if (key > 0 && key < 6) {
return value * 5;
} else { return value;
}});