RysQ
RysQ

Reputation: 348

Parse JSON { "key" : "value" } 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

Upvotes: 3

Views: 6636

Answers (3)

charlietfl
charlietfl

Reputation: 171669

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

Upvotes: 1

devtye
devtye

Reputation: 302

So this is example getting your key and value;

Check console for results: JsFiddle - https://jsfiddle.net/5hpr5bhm/

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

for (var key in data) {
    console.log("User " + data[key] + " is" + key); // "User john is 24"
}

Upvotes: 0

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

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>

Upvotes: 1

Related Questions