sile / jsone

Erlang JSON library
MIT License
291 stars 71 forks source link

Encoding Strings #82

Closed Ndeh-007 closed 10 months ago

Ndeh-007 commented 10 months ago

Hello, I could use some help.

I am trying to encode some data in Erlang but I am having trouble getting the patterns down.

Here's the pre encoding section section of my code

    ...
    Array = [],

    {Type, Priority, _, _, From, To, Msg, Data} = Event,

    %% Type => atom
    %% Priority => integer
    %% From => atom
    %% To => atom
    %% Msg => string
    %% Data => List of tuples: [..., {Key, Value}, ...]
    %%          where Key => atom
    %%                Value => integer or atom

    % create a json encoded instance

    EncodedData = lists:map(fun({Key, Value}) -> #{Key => Value}  end, Data),

    Instance = [
        {<<"type">>, Type},
        {<<"priority">>, Priority},
        {<<"from">>, From},
        {<<"to">>, To},
        {<<"msg">>, Msg},
        {<<"data">>, Data}
    ],

    EncodedArray = [Instance | Array],

    DataJSON = jsone:encode(EncodedArray),

    %% send DataJSON with cowboy 
    ...

Viewing in the browser, I get my output fine except for the msg whose value comes as an array of numbers

image

Please what changes am i to make such that i get a string instead of an array of numbers for the msg key?

sile commented 10 months ago

Erlang's string type is just an alias of "list of integers", and jsone encodes strings as integer lists. To produce JSON strings, you need to pass binaries to the encoding function as follows:

%% strings (i.e., integer lists) are encoded as JSON arrays of integers
1> jsone:encode("hello").
<<"[104,101,108,108,111]">>

%% binaries are encoded as JSON strings
2> jsone:encode(<<"hello">>).
<<"\"hello\"">>

3> jsone:encode(list_to_binary("hello")).
<<"\"hello\"">>
Ndeh-007 commented 10 months ago

It works beautifully. thank you very much.