57 lines
1.3 KiB
JavaScript
57 lines
1.3 KiB
JavaScript
let student = {
|
|
name: 'John',
|
|
age: 30,
|
|
isAdmin: false,
|
|
courses: ['html', 'css', 'js'],
|
|
spouse: null
|
|
}
|
|
|
|
let json = JSON.stringify(student);
|
|
|
|
console.log(typeof json);
|
|
console.log(json)
|
|
|
|
console.log("JSON.stringify to convert objects into JSON")
|
|
console.log(`JSON.stringfy supports following data types:
|
|
- Objects { ... }
|
|
- Arrays [ ... ]
|
|
- Primitives:
|
|
- strings
|
|
- numbers
|
|
- boolean values true/false
|
|
- null
|
|
`);
|
|
|
|
console.log(`JSON.stringfy will skip:
|
|
- Function properties (methods)
|
|
- Symbolic properties
|
|
- Properties that store undefined`);
|
|
|
|
console.log(`object.toJSON() method can be used to customize the JSON.stringfy behavior`);
|
|
let room ={
|
|
number: 23,
|
|
toJSON(){
|
|
return this.number;
|
|
}
|
|
};
|
|
let meeting = {
|
|
title: "Conference",
|
|
room
|
|
};
|
|
console.log(JSON.stringify(meeting));
|
|
|
|
console.log("JSON.parse to convert JSON back into an object");
|
|
console.log("JSON.parse(str, [reviver]) - reviver is a function(key, value) that will be called for each (key, value) pair and can transform the value");
|
|
console.log("value is the value before transformation");
|
|
console.log("for a date, we can use the following reviver");
|
|
|
|
let user = {
|
|
name: "John",
|
|
age: 35
|
|
};
|
|
|
|
let userJSON = JSON.stringify(user);
|
|
console.log(userJSON);
|
|
let user2 = JSON.parse(userJSON);
|
|
console.log(user2);
|