我正在使用ASP.NET MVC創建JSON鍵/值字符串和Javascript來訪問它。我試了幾個例子(見下文),但其中只有一個似乎工作,在那裏我硬編碼元素的id(這顯然不是我想要的)。其他一切都會拋出未定義或異常。爲了澄清,我只是試圖從JSON字符串中獲取值(短語),給定密鑰。從JSON數組訪問字符串值
我的代碼如下。
public string GetNcpJsonDictionary()
{
// Get a list of all dictionary items.
var db = Database.GetDatabase(EnvironmentHelper.IsProduction ? "pub" : "web");
var ncpDictionaryFolder = db.GetItem(ItemIdMapper.Instance.DictionaryNcpItemId);
var ncpDictionaryItems = ncpDictionaryFolder.Axes.GetDescendants().ToList();
var condensedDictionaryItemList = new List<DictionaryItem>();
foreach (var dictionaryItem in ncpDictionaryItems)
{
condensedDictionaryItemList.Add(new DictionaryItem
{
Key = SitecoreApiHelper.GetFieldValue(dictionaryItem.ID.ToString(), "Key"),
Phrase = SitecoreApiHelper.GetFieldValue(dictionaryItem.ID.ToString(), "Phrase")
});
}
var result = JsonConvert.SerializeObject(condensedDictionaryItemList);
return result;
}
在我看來,我把:
<script>
window.ncpDictionary = @Html.Action("GetNcpJsonDictionary", "NCP");
</script>
的Javascript:
var dict = window.ncpDictionary;
if (dict != null) {
$("label[for='AccountBaseModel_Person_Address']").append(dict['we-cannot-deliver-to-po-boxes']);
}
的JSON輸出是這樣的: [{"Key":"some-key","Phrase":"some phrase"},...,...]
調試JS表明我這個..
但是dict['we-cannot-deliver-to-po-boxes']
返回未定義。
我也試過:
dict.we-cannot-deliver-to-po-boxes
dict.getString('we-cannot-deliver-to-po-boxes')
這將工作(但不能用,很明顯):
dict[63]['Phrase']
有可能是一個容易修復那裏,但我沒有找到一個。
所以真的,你有一個奇怪的對象與兩個鍵的數組,一個是'Key'另一個'Phrase',你不能訪問這些對象的價值? – adeneo