2015-04-17 89 views
0

我有一些json:data使用字符串访问json

我有一个字符串的构建,看起来像这样: sections.1.subsections.0.items.0.citation.paragraph

我需要做的是操纵该字符串能够访问data该值。所以把它变成可用的东西: data['sections'][1]['subsections'][0]['items'][0]['citation']['paragraph']

然后用它来改变数据中的值。所以: data['sections'][1]['subsections'][0]['items'][0]['citation']['paragraph'] = 'new value'

我可以在.分割原始字符串,我认为这让我的地方,但我一点儿也不知道如何再重新使用的部件,让我访问该值data

谢谢!

+0

点符号所以转换成数组符号? – jdphenix

+0

但点符号是一个字符串 –

+0

您能解释为什么'sections.1.subsections.0.items.0.citation.paragraph'是一个字符串吗?如果你使用变量,那么'节[1] .subsections [0] .items [0] .citation.paragraph'会给你你想要的 –

回答

3

我还不太确定为什么你要以这种方式处理JSON,但是如果必须这样做,那么你需要使用递归来访问数据。假设我正确映射你的对象,下面的例子应该为你提供一个方法,这样做的:

var data = { 
 
    sections: [ 
 
     { 
 
      subsections: []  
 
     }, 
 
     { 
 
      subsections: [ 
 
       { 
 
        items: [ 
 
         { 
 
          citation: { 
 
           paragraph: "Citation by Warlock"  
 
          } 
 
         } 
 
        ] 
 
       } 
 
      ] 
 
     } 
 
    ] 
 
}; 
 

 
var string = "sections.1.subsections.0.items.0.citation.paragraph", 
 
    parts = string.split('.'); 
 

 
function getValue(tree, index) { 
 
    if(index < (parts.length - 1)) { 
 
     return getValue(tree[parts[index]], index + 1); 
 
    } else { 
 
     return tree[parts[index]]; 
 
    } 
 
} 
 

 
function setValue(tree, index, newValue) { 
 
    if(index < (parts.length - 1)) { 
 
     setValue(tree[parts[index]], index + 1, newValue); 
 
    } else { 
 
     tree[parts[index]] = newValue;  
 
    } 
 
} 
 

 
alert(getValue(data, 0)); 
 
setValue(data, 0, "New Citation By Warlock"); 
 
alert(getValue(data, 0));

的想法是,getValue(...);功能步骤一层深入到你的JSON,然后递归自称。这允许一次一步访问数据,直到检索到最后一部分。然后在所有以前的函数调用中通过递归返回该值。

对于设置值也是一样的想法。 setValue(...);函数一次传入JSON一层,传递新值以设置它,直到它到达最后一个嵌套层。然后为指定的属性设置该值。

编辑:

较好的实施方法是将parts数组传递到getValue(...);setValue(...);功能,以消除外部依赖性。然后,在函数内移动数组的数据值以逐步遍历嵌套图层。这消除了在原有基础上阵列的值指数跟踪的需要:

var data = { 
 
    sections: [ 
 
     { 
 
      subsections: []  
 
     }, 
 
     { 
 
      subsections: [ 
 
       { 
 
        items: [ 
 
         { 
 
          citation: { 
 
           paragraph: "Citation by Warlock"  
 
          } 
 
         } 
 
        ] 
 
       } 
 
      ] 
 
     } 
 
    ] 
 
}; 
 

 

 
var string = "sections.1.subsections.0.items.0.citation.paragraph", 
 
    parts = string.split('.'); 
 

 
function getValue(temp, tree) { 
 
    if(temp.length > 1) { 
 
     tree = tree[temp[0]]; 
 
     temp.shift(); 
 
     return getValue(temp, tree); 
 
    } else { 
 
     return tree[temp[0]]; 
 
    } 
 
} 
 

 
function setValue(temp, tree, newValue) { 
 
    if(temp.length > 1) { 
 
     tree = tree[temp[0]]; 
 
     temp.shift(); 
 
     setValue(temp, tree, newValue); 
 
    } else { 
 
     tree[temp[0]] = newValue;  
 
    } 
 
} 
 

 
alert(getValue(parts, data)); 
 
setValue(parts, data, "New Citation By Warlock"); 
 
alert(getValue(parts, data));

+0

谢谢@ War10ck!这做到了。 可能有更好的方法来处理这一切,但这是我现在需要的。 – awolfe76