30 Days Of JavaScript.16
Day 16. JSON
On
Day 16
, I learned about JSON and its two methods. The methods allows to convert an object to JSON, or JSON to an object.
JSON
JSON stands for ‘JavaScript Object Notation’. The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is for text and string only. JSON is a light weight data format for storing and transporting. JSON is mostly used when data is sent from a server to a client. JSON is an easier-to-use alternative to XML.
1. Difference between JavaScript and JSON
JSON is a syntax for serializing objects, arrays, numbers, string, booleans, and null
. It is based upon JavaScript but is distinct from it: some JavaScript is not JSON.
{
"users": [
{
"firstName": "Ramona",
"lastName": "Doe",
"age": 23,
"country": "Canada"
}
]
}
Above is an example of JSON. It looks similar to a normal object, but the major difference is that the key of a JSON object should be in double quotes, or it should be a string. In a normal object, I can use keys without double quotes. JavaScript Object and JSON are very similar that I can change JSON to Object and Object to JSON.
{
"Ramona": {
"age": 26,
"skills": [
"HTML",
"CSS",
"JavaScript"
]
"isLoggedIn": true,
"points": 50
},
"Brian": {
"age": 22,
"skills": [
"HTML",
"CSS"
]
"isLoggedIn": true,
"points": 40
},
"Josh": {
"age": 28,
"skills": [
"HTML",
"CSS",
"JavaScript",
"React"
]
"isLoggedIn": false,
"points": 70
}
}
Mostly, JSON data is fetched from HTTP response or a file, but I can store JSON as a string and change it to Object for demonstration.
In JavaScript, the keyword JSON
has parse()
and stringify()
methods. When I want to change the JSON to an object, I parse the JSON using JSON.parse()
. When I want to change the object to JSON, I use JSON.stringify()
.
2. Converting JSON to JavaScript Object
1) JSON.parse()
JSON.parse()
method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver
function can be provided to perform a transformation on the resulting object before it is returned. It returns the object, array, string, number, boolean, or null
value corresponding to the given JSON text
.
// put json or text(the data)
JSON.parse(text);
// reviver is an optional callback function
JSON.parse(text, reviver);
- ❌ trailing commas
JSON.parse('[1, 2, 3, ]'); // SyntaxError
JSON.parse('[1, 2, 3]'); // (3) [1, 2, 3]
- ❌ single quotes
JSON.parse("{'age': 25}"); // SyntaxError
JSON.parse("{"age": 25}"); // SyntaxError
// should use different quotes
JSON.parse('{"age": 25}'); // {age: 25}
JSON.parse(`{"age": 25}`); // {age: 25}
const usersText = `{
"Ramona": {
"age": 26,
"skills": [
"HTML",
"CSS",
"JavaScript"
],
"isLoggedIn": true,
"points": 50
},
"Brian": {
"age": 22,
"skills": [
"HTML",
"CSS"
],
"isLoggedIn": true,
"points": 40
}
}`
const usersObj = JSON.parse(usersText);
console.log(usersObj);
2) Using a reviver function with JSON.parse()
To use the reviver function as a formatter, I put the keys and values I want to format.
const usersText = `{
"users": [
{
"firstName": "Ramona",
"lastName": "Doe",
"age": 23,
"country": "Canada"
},
{
"firstName": "Paul",
"lastName": "Doe",
"age": 19,
"country": "Korea"
}
]
}`
// I want to format 'country'
const usersObj = JSON.parse(usersText, (key, value) => {
// using ternary operator
let newValue =
typeof value == 'string' && key == 'country'
? value.toUpperCase()
: value;
return newValue;
});
console.log(usersObj);
3. Converting Object to JSON
1) JSON.stringify()
When I want to change the object to JSON, I use JSON.stringify()
. The method takes one required parameter(value
) and two optional parameters(replacer
, space
). It returns a JSON string that represents the given value, or undefined
.
replacer
is a function that is used to filter the object, naming the properties that should be included in the output.If I don’t want to filter out any keys from the object, I can just pass undefined
or null
.
space
can be a string or number object. It is used to insert white space(indentations) into the output JSON string for readability purposes. If it is a number, it adds the number of spaces. If it is a string, the string is used as white space. The value cannot be longer than 10.
// put json or text(the data)
JSON.stringify(value)
// replacer is an optional callback function
JSON.stringify(value, replacer)
// space is an indentation
JSON.stringify(value, replacer, space)
const users = {
Ramona: {
age: 26,
skills: ['HTML', 'CSS', 'JavaScript'],
isLoggedIn: true,
points: 50
},
Brian: {
age: 22,
skills: ['HTML', 'CSS'],
isLoggedIn: true,
points: 40
}
}
// keep all the keys, 4 indentations
const text = JSON.stringify(users, undefined, 4);
console.log(text);
/*
{
"Ramona": {
"age": 26,
"skills": [
"HTML",
"CSS",
"JavaScript"
],
"isLoggedIn": true,
"points": 50
},
"Brian": {
"age": 22,
"skills": [
"HTML",
"CSS"
],
"isLoggedIn": true,
"points": 40
}
}
*/
The variable name ‘text’ means JSON, because JSON is a string form of an object.
2) Using a filter array with JSON.stringify()
I can use replacer
as a filter when I’m only interested in some keys from the object. I put the keys I want to keep in the array for the output, and use it in the place of the replacer
.
const user = {
firstName: 'Ramona',
lastName: 'Doe',
age: 23,
country: 'Canada',
city: 'Vancouver',
email: 'ramona@ramona.com',
skills: ['HTML', 'CSS', 'JavaScript'],
isLoggedIn: true,
points: 60
}
const text = JSON.stringify(user, ['firstName', 'lastName', 'age', 'country', 'points'], 4);
console.log(text);
/*
{
"firstName": "Ramona",
"lastName": "Doe",
"age": 23,
"country": "Canada",
"points": 60
}
*/
Leave a comment