-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSON.html
More file actions
87 lines (69 loc) · 2.52 KB
/
JSON.html
File metadata and controls
87 lines (69 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JSON</title>
</head>
<body>
<!-- JSON.parse() is a JavaScript method used to convert a JSON string into a JavaScript object. -->
<!-- JSON.stringify is a JavaScript method used to convert a JavaScript object into a JSON string.
-->
<!-- JSON is data format, JS object is a data structure -->
<script>
let products = {
name: "T Shirt",
price: 789,
ratings: {
stars: 4.5,
noOfReviews: 453,
},
};
console.log(typeof products); // object
console.log(products); // {name: 'T Shirt', price: 789, ratings: {…}}
let str = JSON.stringify(products);
console.log(typeof str); // string
console.log(str); // json object {"name":"T Shirt","price":789,"ratings":{"stars":4.5,"noOfReviews":453}}
let newProduct = JSON.parse(str);
console.log(typeof newProduct); // object
console.log(newProduct); // json object to js object
localStorage.setItem("name", "sofian");
localStorage.setItem("price", 789);
console.log(localStorage.getItem("name"));
let product = {
name: "T Shirt",
price: 789,
ratings: {
stars: 4.5,
noOfReviews: 453,
},
};
// localStorage.setItem("product", product); key - product ---- value - [object Object]
localStorage.setItem("product", JSON.stringify(product));
// key - product
// value - {"name":"T Shirt","price":789,"ratings":{"stars":4.5,"noOfReviews":453}}
/* see in localStorage below...
{name: "T Shirt", price: 789, ratings: {stars: 4.5, noOfReviews: 453}}
name : "T Shirt"
price : 789
ratings : {stars: 4.5, noOfReviews: 453}
noOfReviews : 453
stars : 4.5
*/
console.log(localStorage.getItem(product)); // null
console.log(localStorage.getItem("product")); // {"name":"T Shirt","price":789,"ratings":{"stars":4.5,"noOfReviews":453}}
let product2 = JSON.parse(localStorage.getItem("product"));
console.log(product2);
/* {name: 'T Shirt', price: 789, ratings: {…}}
name : "T Shirt"
price : 789
ratings : {stars: 4.5, noOfReviews: 453}
ratings:
noOfReviews: 453
stars: 4.5
*/
localStorage.removeItem("price");
localStorage.clear();
</script>
</body>
</html>