2015-04-17 90 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