spectra_dict_codec (spectra v0.11.2)

View Source

Summary

Functions

Built-in codec for dict:dict(Key, Value).

Functions

decode/7

encode/7

Built-in codec for dict:dict(Key, Value).

Encodes a dict as a JSON object and decodes a JSON object back into a dict. Keys must encode to binary strings when encoding to JSON.

The concrete Key and Value types are extracted from the sp_type() node via spectra_type:type_args/1, so this codec works for any instantiation such as dict:dict(binary(), integer()) or dict:dict(binary(), dict:dict(binary(), float())).

Registering

Add to the application environment before encoding or decoding:

{spectra, [
    {codecs, #{
        {dict, {type, dict, 2}} => spectra_dict_codec
    }}
]}

Example

-type word_counts() :: dict:dict(binary(), non_neg_integer()).

D = dict:from_list([{<<"hello">>, 3}, {<<"world">>, 1}]),
{ok, Json} = spectra:encode(json, my_module, word_counts, D).
%% => {ok, <<"{\"hello\":3,\"world\":1}">>}

{ok, D2} = spectra:decode(json, my_module, word_counts, Json).

schema/6