Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create JSON string in Erlang manually

Tags:

json

erlang

I am new to Erlang and noticed that there is no native function to create json string from lists (Or is there?). I use this method to create json string in Erlang but do not know if it will not malfunction.

Here is an example of my method:

-module(index).
-export([test/0]).

test() ->
    Ma = "Hello World", Mb = "Hello Erlang",
    A = "{\"Messages\" : [\"" ++ Ma ++ "\", \""++Mb++"\"], \"Usernames\" : [\"Username1\", \"Username2\"]}",
    A.

The result is:

388> test().
"{\"Messages\" : [\"Hello World\", \"Hello Erlang\"], \"Usernames\" : [\"Username1\", \"Username2\"]}"
389> 

I think this is the expected result but is there any chance that this method may malfunction when included special characters, such as: <, >, & / \ " ??

What precautions should I take to make this method stronger?


1 Answers

If Ma or Mb contains double quotes or whatever control characters, the parsing from string to JSON will fail. This parsing may never occur in Erlang, as Erlang does not have string to JSON conversion built-in.

It's a good idea to use binaries (<<"I am a binary string">>), as lists consume a lot more resources.

We're using jiffy, which is implemented as a NIF and hence is reasonably fast and it allows for document construction like so:

jiffy:decode(<<"{\"foo\": \"bar\"}">>).
{[{<<"foo">>,<<"bar">>}]}
Doc = {[{foo, [<<"bing">>, 2.3, true]}]}.
{[{foo,[<<"bing">>,2.3,true]}]}
jiffy:encode(Doc).
<<"{\"foo\":[\"bing\",2.3,true]}">>
like image 69
Elwin Arens Avatar answered Dec 01 '25 04:12

Elwin Arens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!