Photo by Ferenc Almasi on Unsplash
JSON [JavaScript Object Notation] is a text-based format used to store and transmit data.
It is written in a "key" : "value"
pair. If enclosed in parentheses, they become an object.
{
"France - Regions":
[
{"name" : "Alsace","capital" : "Strasbourg"},
{"name" : "Île-de-France", "capital" : "Paris"},
//others
]
}
It’s not based on JavaScript, in fact it is language-independent. But since it is similar to how we create objects in JS, we can convert JSON data into JS objects.
Converting JSON data into JS objects
Suppose we have the following string in JS that contains the JSON data we wrote before :
let regionsFrance = `
{"France - Regions":
[
{"name" : "Alsace","capital" : "Strasbourg"},
{"name" : "Aquitaine", "capital" : "Bordeaux"},
{"name" : "Île-de-France", "capital" : "Paris"},
{"name" : "PACA", "capital" : "Marseilles"},
{"name" : "Rhône-Alpes", "capital" : "Lyon"}
]}`;
We convert it into an object using JSON.parse()
and then retrieve the array, which is the value of the key "France - Regions"
:
let objectify = JSON.parse(regionsFrance);
let regions = objectify["France - Regions"];
Then we retrieve the places and locations separately :
let places = regions.map(i => i.name);
let capitals = regions.map(i => i.capital);
console.log(places);
//[ 'Alsace', 'Aquitaine', 'Île-de-France', 'PACA', 'Rhône-Alpes' ]
console.log(capitals);
//[ 'Strasbourg', 'Bordeaux', 'Paris', 'Marseilles', 'Lyon' ]
Stringify()
stringify()
lets you convert JS objects into JSON data.
Consider the following objects :
let newPlace = { name: "Corsica", capital: "Ajaccio" };
let secondNewPlace = { name: "Normandie", capital : "Rouen" };
let jayson = JSON.stringify(newPlace);
let jasonVoorhees = JSON.stringify(secondNewPlace);