Jquery Autocomplete JSON string parsing error

I want to use Jquery autocomplete in my web application but encounter issues. I am developing my application in ASP.NET and JQuery.

Here’s the part of the Autocopmlete ‘succes’ function:

success: function (data) {
     response($.map(data.d, function (item) {
         return {
              label:  item.key,
             value: item.value
            }
       }));
     },

My webservice returns the following JSON:

"[{"key":"Bread","value":"3"}]"

When I run it I get Javascript error:

Uncaught TypeError: Cannot use 'in' operator to search for '42' in [{"key":"bread","value":"3"}]

It looks like that the returned JSON is not in the right format for the $.map function from what I can tell. Also the result might return several items, not just one as seen above.

Can anyone help me solve this issue.
I am using JSON as the dataType and GET as the type in the Ajax call.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I simply suggest you instead of using any other method you can use :

success: function (data, status, xhr) {
    var jsonArray = JSON.parse(data);  // Normal way
}

Other way

success: function (data, status, xhr) {
    var jsonArray = $.parseJSON(data); // using jQuery
}

In this way it will be converted to a simple JavaScript object which you can easily manipulate on your UI/DOM.

Method 2

You’re right — your JSON is an array which contains a single object. You’re expecting just that object.

Try modifying your code like so:

success: function (data) {
  data = data[0];


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x