2012-10-03 72 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的对象。