2012-10-03 128 views
0

完全初學者在這裏。我有jQuery庫。我打電話給返回json的api。我想使用jquery庫中的parseJSON函數來解析它。簡單地說,我不知道如何去做。JSON解析與jquery

我可以找到jQuery庫中的函數,它看起來像這樣:

parseJSON: function(data) { 
    if (typeof data !== "string" || !data) { 
     return null; 
    } 

    // Make sure leading/trailing whitespace is removed (IE can't handle it) 
    data = jQuery.trim(data); 

    // Attempt to parse using the native JSON parser first 
    if (window.JSON && window.JSON.parse) { 
     return window.JSON.parse(data); 
    } 

    // Make sure the incoming data is actual JSON 
    // Logic borrowed from http://json.org/json2.js 
    if (rvalidchars.test(data.replace(rvalidescape, "@") 
     .replace(rvalidtokens, "]") 
     .replace(rvalidbraces, ""))) { 

     return (new Function("return " + data))(); 

    } 
    jQuery.error("Invalid JSON: " + data); 
}, 

我如何通過發送我的JSON?

回答

2
var obj = jQuery.parseJSON(yourJsonObj); 
1

如果使用jQuery.getJSON功能,您可以訪問的API端點,並有響應解析的一個電話。

$.getJSON("/my_resource.json", function(data) { 
    // Use data here 
}); 
0

jQuery的parseJSON()函數會將json轉換爲javascript對象。

,如果你的JSON是,例如:

{ "firstname" : "john", "lastname" : "doe" } 

那麼當你使用parseJSON,你可以訪問屬性,像這樣:

var json = '{ "firstname" : "john", "lastname" : "doe" }'; 
var person = jQuery.parseJSON(json); 

console.log(person.firstname); //will show john 
console.log(person.lastname); //will show doe 

應該讓你開始說。要了解更多信息,請在此處閱讀文檔:http://api.jquery.com/jQuery.parseJSON/

2

如果您使用的是jQuery AJAX命令,則大多數命令都使用dataType參數。將dataType設置爲'json'會自動解析返回的數據。

$.ajax({ 
    url: url, 
    dataType: 'json', 
    data: data, 
    success: callback 
}); 

在這種情況下,數據將最終成爲基於從AJAX調用返回的JSON的對象。