如何重新构建此JSON以便更容易访问

时间:2012-04-30 09:58:44

标签: javascript json

我有一些格式如下的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); 

我希望能够做的只是使用阶段名称来访问数据,而无需在'data'声明后指定索引:

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

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

1 个答案:

答案 0 :(得分:3)

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