Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to access the 2 search results with are returned in a javascript array.

If checked how to do it here: Access / process (nested) objects, arrays or JSON I then tried it based on this resultset:

{
    "responseHeader":{
        "status":0,
        "QTime":2,
        "params":{
            "facet":"false",
            "fl":"id,title,friendlyurl,avatar,locpath,objectid,objecttype",
            "indent":"off",
            "q":"title_search:*castle*",
            "wt":"json",
            "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
            }
        ]
    }

}

for (var i = 0, l = data.response.numFound; i < l; i++) {
    console.log(data.response.docs[i].title);
    console.log(data.response.docs[i].objecttype);
    console.log(data.response.docs[i].friendlyurl);
}

I do get results returned if I call the service directly, I still receive a data=null in my Chrome console log. Why is that happening?

Here is the relevant code

    $("#searchfavs").change(function () {
        $.ajax({
            type: "GET",
            url: "/weddingservice/searchfavoritecompany/?q=" + $("#searchfavs").val(),
            data: "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                data = $.parseJSON(data);
                console.log(data);
                console.log(data.response);
                console.log(data.response.numFound);

                for (var i = 0, l = data.response.numFound; i < l; i++) {
                    console.log(data.response.docs[i].title);
                    console.log(data.response.docs[i].objecttype);
                    console.log(data.response.docs[i].friendlyurl);
                }


            }
        });
        $(this).parent().hide('slow');
    });

How can I loop through my results?

share|improve this question
 
s/result/response? –  PeeHaa Sep 18 '13 at 14:40
 
@PeeHaa: s/result/response? –  Flo Sep 18 '13 at 14:40
1  
Yeh. Either your example dataset is lying or your code is. –  PeeHaa Sep 18 '13 at 14:41
1  
data is a string containing JSON, so you have to parse it first. Since you get an error in that step, your just JSON must be invalid somehow (but what you posted seems to be valid). data.result and data.items won't work because a string doesn't have such properties. You should read the linked question more carefully ;) And don't forget to do console.log(data), console.log(data.response) etc to see which properties the object actually contains. –  Felix Kling Sep 18 '13 at 14:45
1  
Ah: You cannot copy and paste the JSON and put it in a string. You have to escape each \, i.e. "fq":"userid:\"C325D42C-A777-4275-BDD2-D7810A8AB9AB\"" has to be "fq":"userid:\\"C325D42C-A777-4275-BDD2-D7810A8AB9AB\\"" inside the string. –  Felix Kling Sep 18 '13 at 14:50
show 3 more comments

2 Answers

up vote 3 down vote accepted
+50

Your data is NOT JSON. Its JS object already, as you have passed dataType: 'json'. So you dont need to parse it again using data = $.parseJSON(data);

From jQuery docs.

dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)


Also data does not contain any items. It contains response. For convenience the number of found items is in data.response.numFound already. So you can loop like this

for (var i = 0, l = data.response.numFound; i < l; i++) {
    console.log(data.response.docs[i].title);
    console.log(data.response.docs[i].objecttype);
    console.log(data.response.docs[i].friendlyurl);
}

Also note, I just found that your JSON is malformed. JSON must be valid to make this work. Carefully try to understand the comment @FelixKling made.

share|improve this answer
 
But it doesn't fix the issue Uncaught SyntaxError: Unexpected token C. parseJSON seems unhappy with userid:\"C325D42C-A777-4275-BDD2-D7810A8AB9AB\". Ex: jsfiddle.net/45zcz –  Mathieu Imbert Sep 18 '13 at 14:47
 
@MathieuImbert: exactly. I corrected my code like shiplu suggested, but now I still receive the 'Unexpected token C' error. –  Flo Sep 18 '13 at 14:48
 
Oh, I dind't check it. Its clearly a malformed JSON. –  shiplu.mokadd.im Sep 18 '13 at 14:49
2  
@Flo: If you put the JSON in a JS string literal, you have to escape each occurrence of \. The JSON itself is valid, but putting it in a JS literal makes it invalid. –  Felix Kling Sep 18 '13 at 14:50
 
see stackoverflow.com/questions/7167852/jquery-parsejson for similar problem –  Igor Sep 18 '13 at 14:54
show 4 more comments

I found the issue:

Your response data is already an object so no need to parse. When you try to parseJson it returns null.

data = $.parseJSON(data); //remove this line which is returning null and try
console.log(data);
console.log(data.response);
console.log(data.response.numFound);
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.