I have the following JSON string:
{
"responseHeader":{
"status":0,
"QTime":2,
"params":{
"facet":"false",
"fl":"id,title,friendlyurl,avatar,locpath,objectid,objecttype",
"indent":"off",
"q":"title_search:*castle*",
"wt":"json",
"fq":"userid:\"C325D42C-A777-4275-BDD2-D7810A8AB9AB\"",
"defType":"lucene"
}
},
"response":{
"numFound":2,
"start":0,
"docs":[
{
"title":"castle a",
"objecttype":1,
"friendlyurl":"castle-a",
"avatar":"6_887_castle-a.JPG",
"objectid":6
},
{
"title":"castle b",
"objecttype":1,
"friendlyurl":"castle-b",
"avatar":"794_360_13j-castle-by-night.jpg",
"objectid":794
}
]
}
}
There are 2 search results in here: Castle A and Castle B
I want to loop through all results and get the value of the attributes title, objectype and friendlyurl
for testing purposes I simply assigned the JSON string to a variable 'data' I then tried:
for (var i = 0, l = data.items.length; i < l; i++) {
console.log(data.items[i].title);
console.log(data.items[i].objecttype);
console.log(data.items[i].friendlyurl);
}
but then I get: Uncaught TypeError: Cannot read property 'length' of undefined
If I do:
data = $.parseJSON(data);
for (var i = 0, l = data.items.length; i < l; i++) {
console.log(data.items[i].title);
console.log(data.items[i].objecttype);
console.log(data.items[i].friendlyurl);
}
I get: Uncaught SyntaxError: Unexpected token C jquery-1.8.3.min.js:2
the line in the js file: e.JSON.parse(t);
I also tried:
var data = '{"responseHeader":{"status":0,"QTime":1,"params":{"facet":"false","fl":"id,title,friendlyurl,avatar,locpath,objectid,objecttype","indent":"off","start":"0","q":"title_search:*castle*","wt":"json","fq":"userid:\"C325D42C-A777-4275-BDD2-D7810A8AB9AB\"","rows":"10","defType":"lucene"}},"response":{"numFound":2,"start":0,"docs":[{"title":"castle a","objecttype":1,"friendlyurl":"castle-a","avatar":"6_887_castle-a.JPG","objectid":6},{"title":"castle b","objecttype":1,"friendlyurl":"castle-b","avatar":"794_360_13j-castle-by-night.jpg","objectid":794}]}}'
var result,
size = data.result.docs.length,
index;
for (index = 0; index < size; index++) {
result = data.result.docs[index];
console.log(result.title);
}
but that results in error: Uncaught TypeError: Cannot read property 'docs' of undefined.