JSON
JSON is a lightweight format for storing and transporting data between applications. All the most popular programming languages offer support for reading and writing data in JSON.
For Javascript programmers, JSON couldn't be more convenient because it consists basically of Javascript objects. JSON stands for "Javascript Object Notation".
Let's say we have the following object:
var employee = {
'name': "Maria Silva",
'birth_date': '1988-10-01'
};
JSON would be a string representation of that object which is a data type any programming language can interpret. But we know that once something is stored as a string it is hard to retrieve the information we need, like the name of the employee.
We don't need to worry about this because every programming language will have their own methods of importing and exporting data in JSON. In Javascrip we use JSON.stringify() to convert an object into JSON and JSON.parse() to convert JSON into an object.
var employee_json = JSON.stringify(employee);
console.log(employee_json);
typeof employee_json;
// O console will show: '{"name":"Maria Silva","birth_date":"1988-10-01"}'
If we had received that JSON from an external source we could easily convert it back into an object so we could work with it:
var employee_obj = JSON.parse(employee_json);
console.log(employee_obj);
typeof employee_obj;
console.log(employee_obj.name);
Both arrays and objects can be converted into JSON:
var group_A = ['Real Madrid', 'Porto', 'Liverpool', 'Manchester United'];
console.log( JSON.stringify(group_A) );
console.log( typeof JSON.stringify(group_A) ); // The console will show "string"
Using the typeof function we can confirm that JSON is actually a string which makes it lightweight and easy to work with.
In the next section of the course we will learn how to do HTTP requests to APIs to work with external data so we will be dealing with JSON a lot.