javascript - 从 JSON 数组访问字符串值

标签 javascript json asp.net-mvc dictionary

我正在使用 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 向我展示了这一点..

enter image description here

但是 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/

相关文章:

javascript - 不可变性通过解构从对象中删除键

objective-c - cocoa :如何将 NSAttributedString 保存到 JSON

javascript - 我在这个 javascript 循环操作中做错了什么?

c# - 使用C#的电子邮件发送问题

c# - 这两种形式的 Web Api 路由之间的区别?

asp.net - 我是 ASP.NET 程序员 (Webforms)。我应该切换到 MVC 吗?

javascript - React 子组件渲染错误

javascript - 我如何在我的下拉列表中获得年份列表,而不对其进行硬编码,以使用我的 "Add"按钮显示和运行?

javascript - jQuery - 隐藏元素的最佳方式? (以防止元素在实际隐藏之前闪烁)

c# - 在 c# 中验证 android 在应用程序中的购买