JSON是一種輕量級的數據交換格式,常用于Web應用中傳輸數據。在JSON中,數據以鍵值對的形式儲存,可以通過簡單的代碼實現變量賦值。
//JSON格式: var person = { "name": "張三", "age": 25, "isStudent": true, "hobbies": ["看電影", "旅游"] }; //賦值: var name = person.name; //張三 var age = person.age; //25 var isStudent = person.isStudent; //true var hobbies = person.hobbies; //["看電影", "旅游"]
如果JSON數據嵌套,也可以通過類似的方式進行賦值。
//嵌套JSON: var school = { "name": "清華大學", "location": "北京市海淀區", "studentsNum": 30000, "departments": [ { "name": "計算機系", "teacher": "李老師", "students": [ { "name": "張三", "score": 90 }, { "name": "李四", "score": 85 } ] }, { "name": "物理系", "teacher": "王老師", "students": [ { "name": "小明", "score": 95 }, { "name": "小紅", "score": 92 } ] } ] }; //賦值: var csTeacher = school.departments[0].teacher; //李老師 var phyStudentScore = school.departments[1].students[1].score; //92
通過以上代碼可以看出,JSON的賦值方式與JavaScript對象很類似,只需要使用點號或方括號訪問相應的屬性即可。由于JSON數據格式簡潔明了,易于讀寫和理解,因此在Web應用中使用廣泛。
上一篇json怎么賦值js