Paul
Paul

Reputation: 1403

Access string value from JSON array

I'm using ASP.NET MVC to create a JSON key/value string and Javascript to access it. I've tried a few examples (see below) but only one of them seem to work, where I hardcode the id of the element in (which is obviously not what I want). Everything else throws undefined or an exception. To clarify, I'm just trying to get the value (phrase) from the JSON string, given the key.

My code is as follows.

    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;
    }

In my view, I put:

<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']);
}

The JSON outputs like this: [{"Key":"some-key","Phrase":"some phrase"},...,...]

Debugging the JS shows me this..

enter image description here

But dict['we-cannot-deliver-to-po-boxes'] returns undefined.

I've also tried:

dict.we-cannot-deliver-to-po-boxes

dict.getString('we-cannot-deliver-to-po-boxes')

This will work (but can't be used, obviously):

dict[63]['Phrase']

There is probably an easy fix out there, but I haven't found one.

Upvotes: 0

Views: 92

Answers (2)

Amit
Amit

Reputation: 46341

To create a proper dictionary, use Dictionary<TKey, TValue>.

A List<T> is serialized as an array, even if the items of the list are "dictionary like".

When you later try to access the values from the client side JavaScript, you currently use the bracket notation which is typically used for arrays:

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

This will work with objects as well, but it's more common to use the dot notation with a valid key name:

dict.weCannotFeliverToPoBoxes

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68413

But dict['we-cannot-deliver-to-po-boxes'] returns undefined.

because 'we-cannot-deliver-to-po-boxes' is a property value, not property name

This will work (but can't be used, obviously):

dict[63]['Phrase']

why not? dict is obviously an array and each index has an object with key and phrase property.

if you need to search for a specific phrase value in dict array then you need to iterate dict and find a phrase with a specific key

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" ) );

Upvotes: 0

Related Questions