0

I have this type of json input. [ { "id1" : "val1", "id2" : "val2" }, { "id1" : "val3", "id2" : "val4" }, ...]

How do I parse this inside autocomplete plugin available in jquery-ui? Basically I want the val1, val3, etc. corresponding to id1 to be the part of my autocomplete text. Any suggestions on how can I proceed with this?

2
  • Is this from a remote or local data source? Can you show your autocomplete code? Commented May 21, 2012 at 12:53
  • It is from a local data source which I prepared from my sql table. Actually i didn't want to fire "like" query everytime when user enters something. Commented May 22, 2012 at 11:22

2 Answers 2

1

The autocomplete widget expects an array of simple string values or objects with properties label, value or both.

You can take your data and transform it into the proper format using the $.map utility function. This assumes you are making your AJAX request successfully and data is coming back:

$.getJSON("/url", function(data) {
    var src = $.map(function (el) {
        return el.id1;
        // or:
        // return { label: el.id1, value el.id2 };
    });

    $("#id").autocomplete({ 
        source: src
    });
});

Example: http://jsfiddle.net/df6wB/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! It did work. I was also thinking that there should be some mapping possible for the array elements. thanks for your answer. The link was also useful :)
0

To convert JSON string to JSON object use $.parseJSON( ... ). Here var jsonstring is text that contains JSON text and nothing else. parseJSON() will fail if string is not valid JSON.

var jsonobj = $.parseJSON( jsonstring );

Then use that to insert new options to autocomplete.

Get values from jsonobj this way:

alert( jsonobj.id1 ); 
alert( jsonobj.id2 ); 

3 Comments

Here jsonstring is an array as defined in my earlier post. I'm trying that array but the jsonobj is being returned as null. Any pointers on this??
If it is already object then you dont need to $.parseJSON(), you should add more details to your question to get better answers. Few lines of source code is worth more than thousand words.
I'm using this $(document).ready(function () { var sA = []; $.getJSON("URL to my json object array", function(data) { $.each(data, function (i, val) { sA.push(val.v); }); $("#id").autocomplete( { source : sA, minLength: 2, cache : false });

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.