function ShowJson() { var user = { "username": "andy", "age": 20, "info": { "tel": "123456", "cellphone": "98765" }, "address": [ { "city": "beijing", "postcode": "222333" }, { "city": "newyork", "postcode": "555666" } ] } alert(user.username); alert(user.age); alert(user.info.cellphone); alert(user.address[0].city); alert(user.address[1].postcode); user.username = "Tom"; alert(user.username); }
2. There are two ways of parsing a string to JSON object.
//This is a Json string assigned to a variable var user = '{"username": "andy","age": 20,"info": { "tel": "123456", "cellphone": "98765" }}' //First way of parsing it to Json object. In this way, you must add parentheses sign to embrace the string as follows var userObj1 = eval('('+ user + ')'); //Second way of parsing it to Json object.In this way, you must include Json.js which you can download from http://www.json.org/json.js var userObj2 = user.parseJSON();
3.You also can convert a JSON object to JSON String. This is useful when you want to pass the data object to the backend by json format. such as in JQuery ajax
also this method included in JSON.js. (Json.js)
alert(userObj1.toJSONString()); alert(userObj2.toJSONString()); // complete example function showCar() { var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow"); alert(carr.toJSONString()); } function Car(make, model, year, color) { this.make = make; this.model = model; this.year = year; this.color = color; }