我正在使用 ASP.NET MVC 创建 JSON 键/值字符串并使用 Javascript 来访问它。我尝试了几个示例(见下文),但似乎只有其中一个有效,其中我对元素的 id 进行了硬编码(这显然不是我想要的)。其他一切都会抛出未定义或异常。澄清一下,我只是想根据给定的键从 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":"somephrase"},...,...]
调试 JS 向我展示了这一点..
但是 dict['we-cannot-deliver-to-po-boxes']
返回未定义。
我也尝试过:
dict.we-cannot-deliver-to-po-boxes
dict.getString('我们无法投递到邮政信箱')
这会起作用(但显然不能使用):
字典[63]['短语']
可能有一个简单的修复方法,但我还没有找到。
最佳答案
要创建合适的字典,请使用 Dictionary<TKey, TValue>
.
一个List<T>
被序列化为数组,即使列表中的项目是“类似字典”。
当您稍后尝试从客户端 JavaScript 访问值时,您当前使用通常用于数组的方括号表示法:
dict['we-cannot-deliver-to-po-boxes']
这也适用于对象,但更常见的是使用带有有效键名称的点表示法:
dict.weCannotFeliverToPoBoxes
关于javascript - 从 JSON 数组访问字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34796851/