迭代JSON格式的字符串

时间:2015-04-23 03:12:45

标签: javascript ajax json

我使用Ajax将字符串格式的MongoDB查询结果传递给JSP页面。我正在成功检索数据,但不知道如何迭代这些数据。

注意: JSON结构是动态架构,如下所示

以字符串格式查询结果

[
{
   "_id":"...",
   "user":"John Doe",
   "hobbies":["1","2","3"],
   "address":{
      "city":"...",
      "state":"...",
      "country":"..."
   },
   "cell":97265xxxxx
},
{
   "_id":"...",
   "user":"John Doe",
   "hobbies":["1","2","3"],
   "cell":97265xxxxx
}
...
]

首先,我使用jQuery parseJSON()&amp ;;将JSON字符串转换为JavaScript对象。然后我试图循环数据,但它显示我未定义。

这是代码

<button>Click Me</button><br/>
<p id="p0"></p> 
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
<script>
    $(document).ready(function(){
        $("button").on("click",function(){
            $.ajax({
                url:'QuizDemoServlet',
                type:'post',
                success:function(data) {

                    //JSON String is Fetched Successfully
                    $("#p0").html(data);

                    var jso = $.parseJSON(data);
                    alert("JSO " +jso.length);
                    for(var iterate=0; iterate<jso.length; iterate++){
                        $("#p1").append(iterate["user"]+"<br>");
                        $("#p2").append(iterate["hobbies"]+"<br>");
                        $("#p3").append(iterate["cell"]+"<br>");
                    }
                },
                error:function(msg){
                    alert("Error");
                    console.log(msg);
                }
            });
        });
    });
</script>

2 个答案:

答案 0 :(得分:0)

首先,我假设你的JSON是正确的。如果是这样,请确保以这种形式:

[
 {
   "_id":"...",
   "user":"John Doe",
   "hobbies":["1","2","3"],
   "address":{
      "city":"...",
      "state":"...",
      "country":"..."
   },
   "cell":"97265xxxxx"
 },
 {
  "_id":"...",
  "user":"John Doe",
  "hobbies":["1","2","3"],
  "cell":"97265xxxxx"
 },
......
 {

   .....
 }
]

确保使用http://jsonlint.com/

等验证程序进行验证

您的JSON是array of objects。因此,它与在JavaScript中迭代数组一样好。

让我们假设变量data拥有你的JSON。

var data = JSON.parse(YOUR_JSON_STRING); // Your JSON is a `string`. We need to `parse` it to convert into JavaScript object, so that we can iterate over it.

在这种情况下,你可以这样做:

  for(var obj=0;obj<data.length;obj++){
      // You get each object here.
      //obj['_id'] 
      // obj['user']
      // But since schema is dynamic, make sure the key exists before you access it

      if(data[obj].hobbies!= undefined){
          //Iterate over hobbies.
      }

      if(data[obj].address!=undefined){
          var city = data[obj].address.city;
          var state = data[obj].address.state;
          var country= data[obj].address.country;
     }
   ....and so on
  }

答案 1 :(得分:0)

for(var iterate=0; iterate<jso.length; iterate++){ 
   $("#p1").append(jso[iterate].user+"<br>");
   $("#p2").append(jso[iterate].hobbies+"<br>");
   $("#p3").append(jso[iterate].cell+"<br>");
}

Works now