08JSON格式

白茶花约發表於2024-03-14
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <title>Document</title>
 7 
 8     <script>
 9         /*
10             JSON格式的語法
11                 var personStr = '{"屬性名":"屬性值", "屬性名":屬性值, "屬性名":{}, "屬性名":["","",""], "屬性名":[{},{},{}], ...:...}'
12                 屬性名必須用"",屬性值如果是字串,必須用"",數字可以不處理
13         */
14 
15         //一個JSON格式的字串
16         var personStr = '{"name":"張三", "age":20, "dog":{"dname":"小花", "dage":2}, "loveSingers":["張小明","王小東","李小紅"], "friends":[{"fname":"李四"},{"fname":"王五"},{"fname":"趙六"}]}'
17         console.log(personStr)
18        
19         //透過JSON.parse()可以將一個JSON串轉換為一個物件
20         var person = JSON.parse(personStr)
21         console.log(person)
22         console.log(person.name)
23         console.log(person.dog.dname)
24         console.log(person.loveSingers[0])
25         console.log(person.friends[0].fname)
26 
27         //透過 JSON.stringify() 將一個物件轉換為JSON串
28         var personStr1 = JSON.stringify(person)
29         console.log(personStr1)
30 
31     </script>
32 
33 </head>
34 <body>
35     
36 </body>
37 </html>

相關文章