Mangesh
Mangesh

Reputation: 43

Unable to perform for loop on json response object

I have dictionary of categories & their types in .cs file such as

Dictionary<string, List<string>> jsonDic

I have converted it into the json object string using following logic:

JavaScriptSerializer jss = new JavaScriptSerializer();
string barJson = jss.Serialize(jsonDic);
string js = "TypesArray(" + barJson + ")";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Startup1", js, true);

Now, in .js file I am getting following response

enter image description here

As we can see result is not in the form of array I am not able to index tpoints since it is not an array. What should I do? I want to index categories also types assosiated with each category..

Upvotes: 0

Views: 87

Answers (2)

Leo
Leo

Reputation: 14850

I think you are getting very confused with the kind of data structure you're working with. First, you're question title is false...

Unable to perform for loop on json response object

because you are indeed looping through the json objects. When you serialize the object below...

Dictionary<string, List<string>> jsonDic;

the serializer is actually mapping each KeyValuePair object inside the dictionary to a json array item, that is tPoint. So, to iterate through this array all you have to do is the following...

for (var tpoint in tpoints ) {
    tpoint.Foods; //get food array
    tpoint.Foods[0]; //get the first food item

}

and so on, you could even add a nested for loop to iterate through each inner array as below...

for (var tpoint in tpoints ) {

    for(var i = 0; i < tpoint.Foods.length;i++){
        console.log(tpoint.Foods[i]);
    }
}

this will iterate through all food items in every tpoints

Upvotes: 0

djna
djna

Reputation: 55937

You can access any of the attributes by name

 tpoints["Foods"]

and that returns you an array of strings, in the foods case

[Restaurant, Cafe, Bakery]

If you want to iterate,

for (var property in tpoints ) {
    if (tpoints.hasOwnProperty(property)) {
        // do stuff
    }
}

Upvotes: 1

Related Questions