Javascript
/
Types
- 1 Fundamentals 11
-
Hello World
-
Code structure
-
Use strict
-
Variables
-
Data types
-
Type conversions
-
Maths
-
Comparitions
-
Conditional
-
Loops
-
Functions
- 2 Testing 2
-
Mocha
-
Nested describe
- 3 Objects 4
-
Basics
-
Reference
-
Methods
-
Constructor
- 4 Types 5
-
Primitives
-
Numbers
-
Strings
-
Arrays
-
Json
- 5 Classes 3
-
Constructor
-
Binding
-
Inheritance
/
Json
➟
➟
Last update: 27-01-2022
Stringify
We'd like to convert a complex object to string, to send it over network.
/**
* JSON.Stringify ...
* converts objects to string.
*
* The resulting json string is called serialized.
*
* No single quotes or backticks in JSON.
* JSON does not support comments.
*/
let student = {
age: 30,
courses: ['html', 'css'],
};
let json = JSON.stringify(student);
console.log(typeof json);
// string
console.log(json);
// {"age":30,"courses":["html","css"]}
/**
* Nested objects ...
* are supported and converted automatically.
*/
let meetup = {
title: 'Conference',
room: {
number: 3,
users: ['John', 'Mary']
},
};
let meetup_json = JSON.stringify(meetup);
console.log(meetup_json);
// {"title":"Conference","room":{"number":3,"users":["John","Mary"]}}
Parse
To decode a serialized string, we use JSON.parse.
/**
* Parse JSON string
*/
let json = '{"title":"Conference","room":{"number":3}}';
let obj = JSON.parse(json);
console.log(obj);
// { title: 'Conference', room: { number: 3 } }
➥ Questions github Types