【问题标题】:Access string value from JSON array从 JSON 数组访问字符串值
【发布时间】:2016-01-14 18:16:48
【问题描述】:

我正在使用 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":"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,你不能按值访问这些对象?

标签: javascript json asp.net-mvc dictionary


【解决方案1】:

要创建正确的字典,请使用Dictionary&lt;TKey, TValue&gt;

List&lt;T&gt; 被序列化为一个数组,即使列表中的项目是“像字典一样”。

当您稍后尝试从客户端 JavaScript 访问值时,您当前使用通常用于数组的括号表示法:

dict['we-cannot-deliver-to-po-boxes']

也适用于对象,但更常见的是使用带有有效键名的点表示法:

dict.weCannotFeliverToPoBoxes

【讨论】:

  • 这对我不起作用。我从服务器端代码中换掉了我的 JSON 序列化代码,并放入了一些将键和值添加到 Dictionary 的代码,然后我返回了该类型(77 个条目)。在我的 Javascript 中,window.ncpDictionary 未定义..
  • @Paul - 那么你做错了什么。您应该查看生成的 HTML 并准确了解您得到了什么。
【解决方案2】:

但是 dict['we-cannot-deliver-to-po-boxes'] 返回 undefined。

因为'we-cannot-deliver-to-po-boxes' 是属性值,而不是属性名称

这会起作用(但显然不能使用):

dict[63]['短语']

为什么不呢? dict 显然是一个数组,每个索引都有一个具有keyphrase 属性的对象。

如果您需要在 dict 数组中搜索特定的 phrase 值,那么您需要迭代 dict 并找到具有特定键的短语

function findKeyPhrase( someKeyName )
{
    var value = "";
    dict.forEach( function(element){
       if ( element.key == someKeyName )
       {
         value = element.phrase;
       }
    });
    console.log( value );
    return value;
}
console.log( findKeyPhrase ( "we-cannot-deliver-to-po-boxes" ) );

【讨论】:

  • 我试试这个功能。谢谢。使用 ID 是行不通的,因为我的 MVC 代码从可能随时更改的字典中提取项目列表。然后 63 可能会变成 64,或者别的什么,等等。
猜你喜欢
  • 2018-04-14
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 2015-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多