JSON是一種輕量級的數(shù)據(jù)交換格式,在Web應用中得到廣泛的使用。通過使用簡單的文本格式,JSON能夠有效地描述復雜的數(shù)據(jù)結構。本文將介紹如何使用JSON設置數(shù)據(jù)。
//下面是一個簡單的JSON對象 { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] } //這個JSON對象包含了一個人的基本信息,以及地址和電話號碼等。接下來,我們將介紹如何使用JavaScript設置這個JSON對象中的數(shù)據(jù)。 //設置firstName屬性 var obj = {"firstName":"John"}; obj.firstName = "Mike"; console.log(obj.firstName); //輸出:Mike //設置address屬性下的postalCode屬性 obj = { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }; obj.address.postalCode = "10022"; console.log(obj.address.postalCode); //輸出:10022 //在phoneNumbers數(shù)組中添加一個元素 obj.phoneNumbers.push({"type":"cell","number":"123-456-7890"}); console.log(obj.phoneNumbers); //輸出:Array[Object,Object, Object] // 在這里,我們通過簡單的JavaScript來設置JSON對象中的數(shù)據(jù)。JSON對象的屬性可以被讀取和設置,就像JavaScript對象一樣。同時,可以對JSON對象中嵌套的對象和數(shù)組進行更改和擴充。