JavaScript - JSON.parse and JSON.stringify

JavaScript - JSON.parse and JSON.stringify

使用JSON做Client端與Server端資料傳遞的說明與範例。

JSON.parse

目的

目前Client端與Server端溝通的方式大多以JSON字串格式來溝通。從Server端取得JSON字串後,利用JSON.parse()將JSON字串剖析為JavaScript物件供操作使用。

範例 1 - 簡單表示如何將JSON字串剖析為JavaScript物件

var jsonStr = '{"name": "Summer"}';
var parsedObj = JSON.parse(jsonStr);
console.log(parsedObj.name); //Summer

範例 2 - 將JSON字串剖析為JavaScript物件(含陣列,且內含物件)

var jsonStrObjsinArray = '[ { "name": "Apple", "count": "5" }, { "name": "Orange", "count": "6" }]';
var parsedObjinArray = JSON.parse(jsonStrObjsinArray);
console.log(parsedObjinArray); //[Object, Object] 

$.each(parsedObjinArray, function(index, value){
    console.log(value);
});
/*
    Result: 
    Object {name: "Apple", count: "5"}
    Object {name: "Orange", count: "6"}
    Object {name: "Grape", count: "1"}
    Object {name: "Cherry", count: "0"}
    Object {name: "Guava", count: "15"}
    Object {Lemon: "Apple", count: "99"}
*/

Note

  • $.each(collection, function(index, value){}); : 物件或陣列,Ref: .each();
  • collection.each(function(index, value){}); : 物件,Ref: jQuery.each();

範例 3 - 藉由ajax取得JSON字串,然後利用JSON.parse()剖析為JavaScript物件

//ajax response with objs in array (in json format)  
//fake ajax
var dataArray = [];
$.ajax.fake.registerWebservice('/getData', function(data) {
    return {
        "success": true,
        "data" : [
                {
                "title": "宜蘭太平山自行車挑戰",
                "link": "http://www.google.com.tw",
                "thumbnail": "dummy.png",
                "date": "2015/06/06 (六)",
                "startDate": "2015-06-06T10:00",
                "signup": "20150525",
                "location": "新北市政府行市民廣場",
                "streetAddress": "光復南路102號3樓",
                "addressLocality": "台北市",
                "addressRegion": "台灣",
                "latitude": 22.999,
                "longitude": 121.555,
                "tag": [
                    {"link": "/search?keyword=999", "text": "練跑"},
                    {"link": "/search?keyword=888", "text": "夜光路跑"},
                    {"link": "/search?keyword=777", "text": "核心肌群"},
                    {"link": "/search?keyword=666", "text": "PUMA"}
                ]
            },
                {
                "title": "宜蘭太平山自行車挑戰",
                "link": "http://www.google.com.tw",
                "thumbnail": "dummy.png",
                "date": "2015/06/06 (六)",
                "startDate": "2015-06-06T10:00",
                "signup": "20150525",
                "location": "新北市政府行市民廣場",
                "streetAddress": "光復南路102號3樓",
                "addressLocality": "台北市",
                "addressRegion": "台灣",
                "latitude": 22.999,
                "longitude": 121.555,
                "tag": [
                    {"link": "/search?keyword=999", "text": "練跑"},
                    {"link": "/search?keyword=888", "text": "夜光路跑"},
                    {"link": "/search?keyword=777", "text": "核心肌群"},
                    {"link": "/search?keyword=666", "text": "PUMA"}
                ]
            }   
        ],
        "message": "success!"
    }
});    

$.ajax({
    url: '/getData',
    type: 'post',
    fake: true, //fake ajax
    data: JSON.stringify({
        "Data": dataArray
    }),
    dataType: 'json',
    error: function (xhr) {
        alert('噢噢!發生錯誤了!請重新再試一次~');
    },
    success: function (response) {
        console.log(response); //Object {success: true, data: Array[2], message: "success!"}

        $.each(response.data, function(index, value){
            console.log(value);
        }); 

       /*
        Result: 
        Object {title: "宜蘭太平山自行車挑戰", link: "http://www.google.com.tw", thumbnail: "dummy.png", date: "2015/06/06 (六)", startDate: "2015-06-06T10:00"…}
        Object {title: "宜蘭太平山自行車挑戰", link: "http://www.google.com.tw", thumbnail: "dummy.png", date: "2015/06/06 (六)", startDate: "2015-06-06T10:00"…}
        */
    }
}); 

JSON.stringify

目的

當在Clent端操作的JavaScript物件要傳遞給Server端時,使用JSON.stringify()將物件(或陣列,甚至是原始型別)序列化為一個JSON字串,然後將這個JSON字串傳送給Server端。

範例 - 將序列化後的JSON字串利用ajax傳送給Server端

var dataArr = [];
$.ajax({
    url: '/sendData',
    type: 'post',
    data: JSON.stringify({
        "Data": parsedObjinArray //{"Data":[{"name":"Apple","count":"5"},{"name":"Orange","count":"6"}]}
    }),
    dataType: 'json',
    error: function (xhr) {},
    success: function (response) {}
});

Demo / Source Code


推薦閱讀


由於部落格搬家了,因此在新落格也放了一份,未來若有增刪會在這裡更新-JavaScript: JSON.parse and JSON.stringify
張貼留言