I'm trying to look through reddit's API. I have seen a fiddle where they grab the image url from the site. However, I'm confused as to how they are getting the objects themselves. In their each()
statement, they used data.data.children
and item.data.url
, however I cannot find a data object right after another data object in the json here http://www.reddit.com/r/pics.json
. I also do not see item.data.url
. if I look from the very beginning (the two first objects are "kind" and "data"). What does this mean?
Given the code in the fiddle:
$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function(data) {
$.each(data.data.children, function(i,item){
$("<img/>").attr("src", item.data.url).appendTo("#images");
});
});
data
and item
are both function parameters, and their names have no relation to any named key within the JSON.
The parameter data
represents the entire JSON structure, but as it's just a parameter whose name is not significant I shall call it foo
instead to disambiguate it from the contents of that structure, hence foo.data
refers to the child element named data
within the first level of the JSON.
The item
parameter represents each element in the array foo.data.children
, so item.data.url
for the first item would be equivalent to data.children[0].data.url
within the JSON.
The structure of the JSON returned is:
{
data: {
after: "",
before: null,
children: [
{
data: {
url: ""
}
},
...
],
modhash: ""
},
kind: "Listing"
}
The name of the result variable is called data
in the callback function parameters. So to get to the children you need to type:
data.data.children;
Next, in the $.each
loop, each entry from the children
array is assigned to an item
variable in that callback function. It is from there where you drill down to the url
. property ( item.data.url
).
You could name these whatever you want if data.data
is confusing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.