2

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?

Community
  • 1
  • 1
Adam
  • 6,041
  • 36
  • 120
  • 208
  • @PeeHaa: s/result/response? – Adam 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
  • `data.result.docs.length`, but your object has only `data.response.docs.length` – Jakub Kotrs Sep 18 '13 at 14:42
  • 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
  • @FelixKling: I now worked around adding the JSON to a JS string literal and wanted to work directly on the data. You can see it live here: toptrouwen.nl/test2.aspx. If you type 'tic' in the box and exit the input (onblur) a request will be made. Even though I do get results if I call the service directly, I still receive a data=null in my Chrome console log. Any ideas? :) Thanks! – Adam Sep 23 '13 at 17:21
  • Remove the linedata = $.parseJSON(data); from your code. Your data is already a json object. When you parse data, result is invalid. There is some parsing problem. – Adarsh Kumar Sep 27 '13 at 07:09

2 Answers2

3

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.

Community
  • 1
  • 1
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
  • But it doesn't fix the issue _Uncaught SyntaxError: Unexpected token C_. parseJSON seems unhappy with `userid:\"C325D42C-A777-4275-BDD2-D7810A8AB9AB\"`. Ex: http://jsfiddle.net/45zcz/ – Tchoupi 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. – Adam Sep 18 '13 at 14:48
  • 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 http://stackoverflow.com/questions/7167852/jquery-parsejson for similar problem – Igor Sep 18 '13 at 14:54
  • @Flow I get `{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"` from your service – Shiplu Mokaddim Sep 19 '13 at 15:51
  • @shiplu.mokadd.im: sorry for my late reply, I didn't receive a SO notification somehow. The 401 error should now be fixed. Could you try again? Thanks! – Adam Sep 20 '13 at 12:52
  • @shiplu.mokadd.im: any idea what it can be? – Adam Sep 23 '13 at 17:20
  • @Flo just remove `data = $.parseJSON(data);` and it'll work. Se my updated answer for detail information – Shiplu Mokaddim Sep 27 '13 at 07:03
0

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);
Adarsh Kumar
  • 1,134
  • 7
  • 21