Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON { "key" : "value" } JQuery

Tags:

json

jquery

I'm makeing autocomplete fetaure.

This is mine ajax - json - response, representing "id":"name" pairs:

// consloe:
Object {"14":"Mike","15":"John","23":"Drew","45":"Steve","52":"Andrew"}

which i get from:

while($row=$result->fetch_array()){
    $output[$row['user_id']] = $row['user'];
}
echo json_encode($output);

Im trying to make this <div data-user="id">name</div> for each of pair. But I can't handle it.. :/

var results = JSON.parse(data);
$(results).each(function(key, value) {
    $('#results').append('<div class="item">'+ value + '</div>');
})

Code above worked fine while I had only names in json response ($output[] = $row['user'];).

But I need user_id to assign it into input value of chosen option.

This is what I've wright now:

console.log(results);
$(results).each(function(key, value) {
    console.log(key);
    console.log(value);
})

// console:
// Object {"14":"Mike","15":"John","23":"Drew","45":"Steve","52":"Andrew"}
// 0
// {"14":"Mike","15":"John","23":"Drew","45":"Steve","52":"Andrew"}

I'm totally confused

like image 489
RysQ Avatar asked Sep 23 '26 13:09

RysQ


2 Answers

Fix your data structure to be more friendly

Array of objects where each object has the same property names is far more sensible ( and more common)

while($row=$result->fetch_array()){
    $output[] =array('id'=>$row['user_id'], 'user'=> $row['user']);
}
echo json_encode($output);

Will produce:

[{"id":"14","user":"Mike"},{"id":"15","user":"John"}.......]

Now when you iterate the array you have access to the same properties in each iteration. By using these property names it is much easier to read also.

$.each(data, function(arrayIndex, userObject){
   $('#results').append('<div data-user="' + userObject.id+'">'+ userObject.user + '</div>');
});

Also note that arrays are easier to filter and sort and there are lots of native methods for arrays to assist you.

You can also make the property names match your back end for simplicity of updates

like image 107
charlietfl Avatar answered Sep 26 '26 02:09

charlietfl


Iterate through all properties of the object and create div with id and value and then append to #results.

var json = { "14": "Mike", "15": "John", "23": "Drew", "45": "Steve", "52": "Andrew" };

for (var prop in json) {
   $('#results').append('<div id='+prop+'>'+json[prop]+'</div>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"></div>
like image 45
Ibrahim Khan Avatar answered Sep 26 '26 01:09

Ibrahim Khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!