【问题标题】:How to parse JSON in loop如何在循环中解析 JSON
【发布时间】:2013-02-28 11:48:31
【问题描述】:

这里是 Javascript 的新手。我在用 JQuery 解析一些 JSON 时遇到了一点麻烦。我相信这取决于我的 JSON 的结构,但是因为我将这些脚本用于其他服务,所以不想改变那里的结构。

我的JSON如下

{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack   Black","auto_id":"22"}]}

理想情况下,我希望使用 customer_name 来填充列表视图,并且我还想将 auto_id 保存在某处(可能是本地存储),因此如果选择我可以显示相关数据。

如果有人可以帮助我构建一个循环来解析这个 JSON,我将不胜感激。

【问题讨论】:

    标签: jquery json jquery-mobile


    【解决方案1】:

    你可以使用jQuery轻松解析它。

    $.parseJSON(data); 
    

    试试这个:

    var json = $.parseJSON(data);
    for(var i=0; i<json.customerInAccount.length; i++){
         // do your stuff here..
    }
    

    如果你有任何问题,请告诉我

    【讨论】:

      【解决方案2】:

      您可以按照以下方式进行操作。

      $('#home').live('pageshow', function(){
          // creating object 
          var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack   Black","auto_id":"22"}]}');
      
          // creating html string
          var listString = '<ul data-role="listview" id="customerList">';
      
          // running a loop
          $.each(customerList.customerInAccount, function(index,value){
           listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
          });
          listString +='</ul>';
      
          console.log(customerList);
      
          //appending to the div
          $('#CustomerListDiv').html(listString);
      
          // refreshing the list to apply styles
          $('#CustomerListDiv ul').listview();
      
          // getting the customer id on the click
          $('#customerList a').bind('click',function(){
           var customerID = $(this).data('cusid');  
           alert(customerID);
          });
      });
      

      您可以在此处查看活跃的工作小提琴。 http://jsfiddle.net/amEge/3/

      【讨论】:

      • 前两个答案很好,向我解释了很多,这让我可以访问和填充我的列表,但你的回答走得更远,向我展示了如何在点击时访问 id 变量,这非常有用,非常感谢大家。
      【解决方案3】:

      这样使用

      var value=yourJsonString
      var results=JSON.parse(value); 
      
      $.each(results.customerInAccount,function(i,item){
       // do with item 
      alert(  item.customer_name);
      });
      

      工作演示:JSON parse with loop

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多