0

我有一些格式如下的 JSON 数据:

 [ {"stage1" : [{
        "checkpoints" : 
            [
                { 
                    "id" : "checkpoint1",
                    "name" : "a checkpoint name 1",
                    "purpose" : "a string about the purpose here", 
                                         },
                 { 
                    "id" : "checkpoint2",
                    "name" : "a checkpoint name 2",
                    "purpose" : "a string about the purpose here", 

                 }
             ],                      

          "stages" : 
                  [
                     {

                     "id" : "an id here",
                     "name" : "a checkpoint name 1",
                     "purpose" : "a string about the purpose here yah", 

                     } 
             ]          
         }
     ]},

   {"stage2" : [{
        "checkpoints" : 
            [
                { 
                    "id" : "checkpoint1",
                    "name" : "a checkpoint name 1",
                    "purpose" : "a string about the purpose here", 
                                         },
                 { 
                    "id" : "checkpoint2",
                    "name" : "a checkpoint name 2",
                    "purpose" : "a string about the purpose here", 

                 }
             ],                      

          "stages" : 
                  [
                     {

                     "id" : "an id here",
                     "name" : "a checkpoint name 1",
                     "purpose" : "a string about the purpose here yah", 

                     } 
             ]          
         }
     ]},

     {"stage3" : [{
        "checkpoints" : 
            [
                { 
                    "id" : "checkpoint1",
                    "name" : "a checkpoint name 1",
                    "purpose" : "a string about the purpose here", 
                                         },
                 { 
                    "id" : "checkpoint2",
                    "name" : "a checkpoint name 2",
                    "purpose" : "a string about the purpose here", 

                 }
             ],                      

          "stages" : 
                  [
                     {

                     "id" : "an id here",
                     "name" : "a checkpoint name 1",
                     "purpose" : "a string about the purpose here yah", 

                     } 
             ]          
         }
     ]},





                         ]

目前我必须参考这样的数据才能进入一个阶段:

alert(data[0].stage1[0].checkpoints.length);  

为了获得第 2 阶段的数据,我必须这样做:

alert(data[1].stage2[0].checkpoints.length); 

我想要做的只是使用阶段名称来访问数据,而不必在“数据”声明之后指定索引:

alert(data.stagex[0].checkpoints.length); 

我不想在数据部分之后声明索引。如何重组我的 JSON,以便我可以使用阶段名称来获取我需要的数据,而无需先指定索引?

4

1 回答 1

3

不要将 Stage1、Stage2 放在数组中。它们可以作为键直接访问

于 2012-04-30T10:01:51.723 回答