代码改变世界

js 解析json数据方法

2012-03-21 22:49  javaspring  阅读(209)  评论(0编辑  收藏  举报

1.解析json 纯数组形式

[{"kl_id":"1","kl_title":"Test1"},{"kl_id":"2","kl_title":"Test2"}]

<META NAME="Description" CONTENT="">
<script language="javascript">
function showJson()
{
    var json=  [{"kl_id":"1","kl_title":"Test1"},{"kl_id":"2","kl_title":"Test2"}];
    var str = ""; 
    //第一种写法
    for (var one in json)
    {
        for(var key in json[one])
        {
              
            str += json[one][key] + ",";
        }
    } 
     //第二种写法
    //for (var one in json)
  //  {
       //     str += json[one].kl_id+ ",";
         //   str += json[one].kl_title + ",";  
    //} 
    document.form.txtName.value = str;
}
</script>
</HEAD>
<BODY>
<form name="form">
  <a href="#" onclick="showJson();">Click</a>
  <br>
  <input name="txtName" value="" type="text" size="50">
  </form>
</BODY>
</HTML> 

2.解析json 比较复杂的类型

{"address":[{"kl_id":"1","kl_title":"Test1"},{"kl_id":"2","kl_title":"Test2"}]}

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<script language="javascript">
function showJson()
{
    var json=  {"address":[{"kl_id":"1","kl_title":"Test1"},{"kl_id":"2","kl_title":"Test2"}]};
    var str = "";
    //第一种写法
     for (var one in json.address) {
    
          for(var key in json.address[one]){
         
          }
            str += json.address[one][key] + ",";     
    }
     //第二种写法
     //for (var one in json.address)
   // {
      //      str += json.address[one].kl_id+ ",";
     //          str += json.address[one].kl_title + ",";  
   // }
    document.form.txtName.value = str;
}
</script>
</HEAD>

<BODY>
<form name="form">
  <a href="#" onclick="showJson();">Click</a>
  <br>
  <input name="txtName" value="" type="text" size="50">
  </form>
</BODY>
</HTML>