Loop through json data using javascript



In this article I am going to explain about how to loop through the JSON. It is explained using two drop down values which means for city and std codes.


In  our code we have two drop down lists. One for selecting city and another one for loading the corresponding stdcodes. The javascript function is used to loop through this json data. In this javascript code we first removing all the items from the stdcode dropdown. After that we are getting the comma separated values of the particular selected city. Then we are splitting the comma separated stdcodes and loading it to the stdcode drop down. The source code for this is given below


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<form id="form1" runat="server">
<asp:DropDownList runat="server" ID="city" onchange="loadSTDCode(this.value);">
<asp:ListItem Text="Select City" Value="" />
<asp:ListItem Text="Bangalore" Value="0" />
<asp:ListItem Text="Chennai" Value="1" />
<asp:ListItem Text="Delhi" Value="2" />

<asp:DropDownList ID="stdcode" runat="server">
<script type="text/javascript">
function loadSTDCode(cityid) {
var list = document.getElementById('<%=stdcode.ClientID %>');
var optlength = list.options.length;
for (var i = 0; i < optlength; i++) {

var city = 'c' + cityid;

var arr = [{ "c1": "562,343,534", "c2": "79,123,124,967", "c3": "532", "c4": "183", "c5": "240", "c6": "80", "c0": "1521,1522,1520,151,1523"}];
for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];
    for (var key in obj) {
        var attrName = key;

        var attrValue = obj[key];
        if (attrName == city) {

            var posi = attrValue.indexOf(",");
            if (posi == -1) {
                var opt = document.createElement("option");
                document.getElementById('<%=stdcode.ClientID %>').options.add(opt);
                opt.text = attrValue;
                opt.value = attrValue;
            else {
                var mySplitResult = attrValue.split(",");
                for (var i = 0; i < mySplitResult.length; i++) {
                    var opt = document.createElement("option");
                    document.getElementById('<%=stdcode.ClientID %>').options.add(opt);
                    opt.text = mySplitResult[i];
                    opt.value = mySplitResult[i];

If you have any doubts in above code then enter it in comments.

Do you like this article. Then comment here or share with your friends. Or like our Facebook  page.

1 comment:

  1. Good work kanna.. Keep it up..


Online Casino