javascript 解析json

來源:互聯網
上載者:User

JSON (JavaScript Object Notation)一種簡單的資料格式,比xml更輕巧。 JSON 是JavaScript 原生格式,這意味著在 JavaScript 中處理 JSON 資料不需要任何特殊的 API 或工具包。

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

舉個簡單的例子:

js 代碼
  1. function showJSON() {   
  2.     var user =    
  3.     {    
  4.         "username":"andy",   
  5.         "age":20,   
  6.         "info": { "tel": "123456", "cellphone": "98765"},   
  7.         "address":   
  8.             [   
  9.                 {"city":"beijing","postcode":"222333"},   
  10.                 {"city":"newyork","postcode":"555666"}   
  11.             ]   
  12.     }   
  13.        
  14.     alert(user.username);   
  15.     alert(user.age);   
  16.     alert(user.info.cellphone);   
  17.     alert(user.address[0].city);   
  18.     alert(user.address[0].postcode);   
  19. }   

這表示一個user對象,擁有username, age, info, address 等屬性。

同樣也可以用JSON來簡單的修改資料,修改上面的例子

js 代碼
  1. function showJSON() {   
  2.     var user =    
  3.     {    
  4.         "username":"andy",   
  5.         "age":20,   
  6.         "info": { "tel": "123456", "cellphone": "98765"},   
  7.         "address":   
  8.             [   
  9.                 {"city":"beijing","postcode":"222333"},   
  10.                 {"city":"newyork","postcode":"555666"}   
  11.             ]   
  12.     }   
  13.        
  14.     alert(user.username);   
  15.     alert(user.age);   
  16.     alert(user.info.cellphone);   
  17.     alert(user.address[0].city);   
  18.     alert(user.address[0].postcode);   
  19.        
  20.     user.username = "Tom";   
  21.     alert(user.username);   
  22. }   

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

js 代碼
  1. function showCar() {   
  2.     var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow");   
  3.     alert(carr.toJSONString());   
  4. }   
  5.   
  6. function Car(make, model, year, color)       {   
  7.      this.make  =  make;   
  8.      this.model  =  model;   
  9.      this.year  =  year;   
  10.      this.color  =  color;   
  11. }   

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

js 代碼
  1. function myEval() {   
  2.     var str = '{ "name": "Violet", "occupation": "character" }';   
  3.     var obj = eval('(' + str + ')');   
  4.     alert(obj.toJSONString());   
  5. }   

或者使用parseJSON()方法

js 代碼
  1. function myEval() {   
  2.     var str = '{ "name": "Violet", "occupation": "character" }';   
  3.     var obj = str.parseJSON();   
  4.     alert(obj.toJSONString());   
  5. }   

下面使用prototype寫一個JSON的ajax例子。

先寫一個servlet (我的是servlet.ajax.JSONTest1.java)就寫一句話

java 代碼
  1. response.getWriter().print("{ \"name\": \"Violet\", \"occupation\": \"character\" }");  

再在頁面中寫一個ajax的請求

js 代碼
  1. function sendRequest() {   
  2.     var url = "/MyWebApp/JSONTest1";   
  3.     var mailAjax = new Ajax.Request(   
  4.         url,   
  5.         {   
  6.             method: 'get',   
  7.             onComplete: jsonResponse   
  8.         }   
  9.     );   
  10. }   
  11.   
  12. function jsonResponse(originalRequest) {   
  13.     alert(originalRequest.responseText);   
  14.     var myobj = originalRequest.responseText.parseJSON();   
  15.     alert(myobj.name);   
  16. }   

prototype-<st1:chsdate w:st="on" isrocdate="False" islunardate="False" day="30" month="12" year="1899">1.5.1</st1:chsdate>.js中提供了JSON的方法,String.evalJSON(), 可以不使用json.js, 修改上面的方法

js 代碼
  1. function jsonResponse(originalRequest) {   
  2.     alert(originalRequest.responseText);   
  3.     var myobj = originalRequest.responseText.evalJSON(true);   
  4.     alert(myobj.name);   
  5. }   

JSON還提供了java的jar包 http://www.json.org/java/index.html API也很簡單,下面舉個例子

在javascript中填加請求參數

js 代碼
  1. function sendRequest() {   
  2.     var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow");   
  3.     var pars = "car=" + carr.toJSONString();   
  4.   
  5.     var url = "/MyWebApp/JSONTest1";   
  6.     var mailAjax = new Ajax.Request(   
  7.         url,   
  8.         {   
  9.             method: 'get',   
  10.             parameters: pars,   
  11.             onComplete: jsonResponse   
  12.         }   
  13.     );   
  14. }   

使用JSON請求字串就可以簡單的產生JSONObject並進行解析,修改servlet添加JSON的處理(要使用json.jar)

java 代碼
  1. private void doService(HttpServletRequest request, HttpServletResponse response) throws IOException {   
  2.         String s3 = request.getParameter("car");   
  3.         try {   
  4.             JSONObject jsonObj = new JSONObject(s3);   
  5.             System.out.println(jsonObj.getString("model"));   
  6.             System.out.println(jsonObj.getInt("year"));   
  7.         } catch (JSONException e) {   
  8.             e.printStackTrace();   
  9.         }   
  10.         response.getWriter().print("{ \"name\": \"Violet\", \"occupation\": \"character\" }");   
  11.     }   

同樣可以使用JSONObject產生JSON字串,修改servlet

java 代碼
  1. private void doService(HttpServletRequest request, HttpServletResponse response) throws IOException {   
  2.         String s3 = request.getParameter("car");   
  3.         try {   
  4.             JSONObject jsonObj = new JSONObject(s3);   
  5.             System.out.println(jsonObj.getString("model"));   
  6.             System.out.println(jsonObj.getInt("year"));   
  7.         } catch (JSONException e) {   
  8.             e.printStackTrace();   
  9.         }   
  10.            
  11.         JSONObject resultJSON = new JSONObject();   
  12.         try {   
  13.             resultJSON.append("name", "Violet")   
  14.                       .append("occupation", "developer")   
  15.                       .append("age", new Integer(22));   
  16.             System.out.println(resultJSON.toString());   
  17.         } catch (JSONException e) {   
  18.             e.printStackTrace();   
  19.         }   
  20.         response.getWriter().print(resultJSON.toString());   
  21.     }   
js 代碼
  1. function jsonResponse(originalRequest) {   
  2.     alert(originalRequest.responseText);   
  3.     var myobj = originalRequest.responseText.evalJSON(true);   
  4.     alert(myobj.name);   
  5.     alert(myobj.age);   
  6. }  

參考

http://www.json.org/js.html

http://www.blogjava.net/Jkallen/archive/2006/03/28/37905.html

http://www.json.org/

http://www.prototypejs.org/learn/json

http://www.json.org/java/index.html

http://www.ibm.com/developerworks/cn/web/wa-ajaxintro10/index.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.