From 7bec5f3111c7d77d518329c1a57f3c2643939a19 Mon Sep 17 00:00:00 2001 From: Hanzhang ma Date: Sat, 22 Jun 2024 22:32:05 +0200 Subject: [PATCH] JSON Methods --- 5.11JSONMethods/t.js | 56 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 5.11JSONMethods/t.js diff --git a/5.11JSONMethods/t.js b/5.11JSONMethods/t.js new file mode 100644 index 0000000..e8848e6 --- /dev/null +++ b/5.11JSONMethods/t.js @@ -0,0 +1,56 @@ +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);