spectra_dict_codec (spectra v0.11.2)
View SourceSummary
Functions
-spec decode(atom(), module(), spectra:sp_type_reference(), dynamic(), spectra:sp_type(), term(), spectra:sp_config()) -> spectra:codec_decode_result().
-spec encode(atom(), module(), spectra:sp_type_reference(), dynamic(), spectra:sp_type(), term(), spectra:sp_config()) -> spectra:codec_encode_result().
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).
-spec schema(atom(), module(), spectra:sp_type_reference(), spectra:sp_type(), term(), spectra:sp_config()) -> dynamic().