Jquery每个循环以获取json数据

时间:2016-12-26 13:37:44

标签: jquery json each

我在json中有这些数据,我想加载它并在localStorage中使用它。

[
{
    "name": "Dexter",
    "year": "2006",
    "rating": "88%",
    "from": "USA",
    "kind": "crime / drama / thriller",
    "length": "96x55 min",
    "characters": [
      {
         "name": "Dexter Morgan",
         "actor": "Michael C. Hall"
      },
      {
         "name": "Debra Morgan",
         "actor": "Jennifer Carpenter"
      },
      {
         "name": "Angel Batista",
         "actor": "David Zayas"
      },
      {
         "name": "Hannah McKay",
         "actor": "Yvonne Strahovski"
      },
      {
         "name": "Joey Quinn",
         "actor": "Desmond Harrington"
      }
    ]
}, ... (+other tv series)]

这是我加载数据并将其传递给var jsonObj的代码,我用它来加载到localStorage。

function loadData(){

    $.getJSON("data.json",function(data){
     $.each(data, function(key, val){

          var charactersArray = [];

          $.each(data.characters, function(key, val){

              charactersArray += {
                    name: val.name,
                    actor: val.actor
              };
          }); 

          var jsonObj = { 
                          name: val.name, 
                          year: val.year, 
                          rating: val.rating, 
                          from: val.from, 
                          kind: val.kind,  
                          length: val.length, 
                          characters: charactersArray
                        };....

这里唯一不起作用的是迭代获取charactersArray的值。它是空的,结果中只包含[]。有人可以帮我解决这个问题,以获取var jsonObj的相关数据吗?非常感谢你。

1 个答案:

答案 0 :(得分:0)

我已编辑了部分代码,如下所示希望这会有用。

$.each(data, function(key, val){
      var charactersArray = [];

      $.each(val.characters, function(ChildKey, ChildVal){
          charactersArray += {
                name: ChildVal.name,
                actor: ChildVal.actor
          };
      }); 

      var jsonObj = { 
                      name: val.name, 
                      year: val.year, 
                      rating: val.rating, 
                      from: val.from, 
                      kind: val.kind,  
                      length: val.length, 
                      characters: charactersArray
                    };});