Dynamics 365 Business Central – JSON Object into a Dictionary Data Type

The Dictionary Data Type represents an unordered collection of keys and values and is optimized for fast lookup of values. Each addition to the dictionary consists of a value and its associated key. Every key in a Dictionary must be unique. It is on my list of favorite “new” AL Data Types, and I find it often easier to work with a dictionary than another object type.

In this example, a JSON Object’s value keys (not the array or object keys) are copied into a Dictionary Data Type variable.

procedure JsonObjectValuestoDictionary(JObject: JsonObject; var ObjectDictionary: Dictionary of [Text, Text])
var
    IsHandled: Boolean;
    JsonToken: JsonToken;
    DuplicateKeyErr: label 'Duplicate Key %1', Comment = '%1 Key Name';
    ObjectKeys: List of [Text];
    JKey: Text;
    JValue: Text;
begin
    Clear(ObjectDictionary);

    OnBeforeJsonObjectValuestoDictionary(JObject, ObjectDictionary, IsHandled);
    if IsHandled then
        exit;

    ObjectKeys := JObject.Keys();
    foreach JKey in ObjectKeys do begin
        JObject.Get(Jkey, JsonToken);
        if JsonToken.IsValue then begin
            if ObjectDictionary.ContainsKey(JKey) then
                Error(DuplicateKeyErr, JKey);
            JsonToken.WriteTo(JValue);
            ObjectDictionary.Add(DelChr(JKey, '=', '"'), DelChr(JValue, '=', '"'));
        end;
    end;

    OnAfterJsonObjectValuestoDictionary(JObject, ObjectDictionary);
end;

[BusinessEvent(false)]
local procedure OnAfterJsonObjectValuestoDictionary(JObject: JsonObject; var ObjectDictionary: Dictionary of [Text, Text])
begin
end;

[BusinessEvent(false)]
local procedure OnBeforeJsonObjectValuestoDictionary(JObject: JsonObject; var ObjectDictionary: Dictionary of [Text, Text]; var Handled: Boolean)
begin
end;
You can learn more about Dictionary Data Types in Dynamics 365 Business Central here.

Note: The code and information discussed in this article are for informational and demonstration purposes only. This content was created referencing Microsoft Dynamics 365 Business Central 2022 Wave 2 online.

2 comments

    • Tonya on March 23, 2023 at 4:30 pm
    • Reply

    You just saved me a TON of time!
    Working with Azure DevOps API, and custom fields are named “Custom.Field Name”
    You can’t get the value using dot notation!
    Came across your blog post, put the data in a Dictionary, and bam! I have my value.
    Thank you!!

    1. Thank you for the the feedback! I am happy to hear that this helped you with your task!

Leave a Reply

Your email address will not be published.