Reputation: 315
NET guy here, so i'm very rusty at Javascript (or JQuery for that matter)
I serialized a list from server side .NET that i need to access on the client side. The string result is in the following format.
[{"id":"1","name":"xxx"},{"id":"2","name":"yyy"}]
How do i iterate through this in Javascript? I'm having a hard time actually get the values in the array. I end up iterating through each character of the JSON string.
function BuildList() {
var result = '<%= JSON %>';
for (var obj in result) {
alert("Obj: " + obj);
for (var property in result[obj]) {
alert(property + "value: " + result[obj][property]);
}
}
}
Upvotes: 0
Views: 105
Reputation: 48425
Javascript has built in function to convert JSON to a javascript object, try this:
var myObject = JSON.parse(myJSONtext);
This code example was taken from here, where you can read a lot more about it.
With your example, it could be used like so:
var result = '<%= JSON %>';
var resultObject = JSON.parse(result);
var firstId = resultObject[0].id;
Upvotes: 2
Reputation: 337600
You can use $.parseJSON()
to parse the string literal to an object, and then you can loop through the properties of that object.
function BuildList() {
var result = '[{"id":"1","name":"xxx"},{"id":"2","name":"yyy"}]';
var resultObject = $.parseJSON(result);
$.each(resultObject, function(key, value) {
alert("Obj: " + + value.id + ' / ' + value.name);
})
}
BuildList()
Upvotes: 0