mflair2000
mflair2000

Reputation: 315

Javascript Iterate over .NET SerializedJson

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

Answers (2)

musefan
musefan

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;

Here is a working example

Upvotes: 2

Rory McCrossan
Rory McCrossan

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()

Example fiddle

Upvotes: 0

Related Questions