JavaScript -- 使用JavaScript解析JSON格式的字串

來源:互聯網
上載者:User

標籤:javascript   json   

JSON的規則很簡單:對象是一個無序的“‘名稱/值’對”集合。一個對象以“{”(左括弧)開始,“}”(右括弧)結束。每個“名稱”後跟一個“:”(冒號);“‘名稱/值’對”之間使用“,”(逗號)分隔。具體細節參考http://www.json.org/json-zh.html

一直以來解析JSON都是使用的org.json包,進行的後台解析,
http://blog.csdn.net/gaopeng0071/article/details/25873407
現在這裡轉載下前台的解析方式。

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[0].postcode); } 

這表示一個user對象,擁有username, age, info, address 等屬性。
同樣也可以用JSON來簡單的修改資料,修改上面的例子

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[0].postcode); user.username = "Tom"; alert(user.username); }

JSON提供了json.js包,下載http://www.json.org/json.js 後,將其引入然後就可以簡單的使用object.toJSONString()轉換成JSON資料。

更多用法參考:http://www.jb51.net/article/21452.htm

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; } 

可以使用eval來轉換JSON字元到Object

function myEval() { var str = ‘{ "name": "Violet", "occupation": "character" }‘; var obj = eval(‘(‘ + str + ‘)‘); alert(obj.toJSONString()); } 

或者使用parseJSON()方法

function myEval() { var str = ‘{ "name": "Violet", "occupation": "character" }‘; var obj = str.parseJSON(); alert(obj.toJSONString()); } 

JavaScript -- 使用JavaScript解析JSON格式的字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.