I've been looking through Stackoverflow for answers and there seems to be more than one way of serializing (converting the JSON response back into HTML and/or other code so we may do something useful with it).
The way I am using is this..
$.getJSON(
"https://www.googleapis.com/shopping/search/v1/public/products?callback=?",
{
开发者_C百科 key: "unique key code",
country: "US",
q: "iphone",
alt: "json"
},
function(data)
{
$.each(data.items, function(i, item)
{
//Do something with each object
}
}
So I'm using the $.getJSON method to retrieve the JSON response then looping through each object and doing something.
Is this way fine? Should I be using another function to retrieve the JSON response?
Regards, LS
if you set dataType
to json
jquery parses json for you
$.ajax({
dataType:"json",
...
success:function(data){
$.each(data.items, function(i, item)
{
//Do something with each object
}
}
});
No, you are doing it perfectly fine. jQuery handles the conversion of "string" to json data and back.
There are native implementations of converting to and from JSON within browsers, however it is important to note that older browsers do not support this out of the box. You should include the json2.js
library to ensure JSON support.
var dataJson={"something":"special"};
var jsonString=JSON.stringify(dataJson);
var dataJsonAgain=JSON.parse(jsonString);
jQuery has an additional hack in how it parses JSON if there is no native implementation, without using eval, since eval is evil! It looks somewhat like this;
(new Function("return "+dataJson))()
simplest way would be to stick to jQuery and its parseJSON
function that does the polyfill for you.
精彩评论