0

To send an erlang data in json can be done by the following:

ReqBody = << "{\"snippet\":\"Body\" }" >>

But if I have an variable like

Temp = "data from erlang" 

how can I add Temp in this format??

radrow
  • 6,419
  • 4
  • 26
  • 53
sujays
  • 151
  • 12
  • Use a library [https://github.com/search?utf8=✓&q=erlang+json](https://github.com/search?utf8=✓&q=erlang+json) – Lol4t0 Jun 16 '16 at 07:40
  • Possible duplicate of [What is the most mature JSON library for Erlang](http://stackoverflow.com/questions/2395992/what-is-the-most-mature-json-library-for-erlang) – legoscia Jun 17 '16 at 10:47
  • Seems like a decent percentage of Erlang questions is about JSON... – Elwin Arens Jun 17 '16 at 13:58

4 Answers4

4

For producing JSON you definitely should use one of JSON libraries which are better tested than your own code. I can recommend pure Erlang jsone or NIF jiffy. Do not forget that each of them needs to convert your term to proper structure.

Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73
0
>T = {"Temp","data from erlang"}.
>t2j:t2jp(T).
{"Temp":"data from erlang")

you can use my tuple to json module, or one of many others.

Roman Rabinovich
  • 868
  • 6
  • 13
-1

You can convert Temp via http://erlang.org/doc/man/erlang.html#list_to_binary-1

And then do the same.

Derek Brown
  • 491
  • 3
  • 7
-1

I'd avoid generating JSON by string concatenation. Unless you validate the inputs very carefully it's likely that someone could (intentionally or not) sneak, say, a quote into a string and break everything.

If you're going to both parse and generate JSON, I suggest you use one of the open source JSON libraries for Erlang.

If all you need is to generate JSON, you probably don't need a library. You could use something like this as a starting point (caveat emptor: untested code, probably has plenty of bugs):

encode(Term) ->
    iolist_to_binary(encode1(Term)).

encode1(Term) when is_binary(Term) -> Term;
encode1(true) -> <<"true">>;
encode1(false) -> <<"false">>;
encode1(Term) when is_atom(Term) -> encode1(atom_to_list(Term));
encode1(Term) when is_integer(Term) -> list_to_binary(integer_to_list(Term));
encode1(Term=[{_, _}|_]) -> % assume object if it starts with a tuple
    [<<"{">>,
     join([[encode1(K), <<":">>, encode1(V)] || {K, V} <- Term], <<",">>),
     <<"}">>];
encode1(Term) when is_list(Term) ->
    case io_lib:printable_list(Term) of
        true ->
            [list_to_binary(io_lib:format("~p", [Term]))];
        false ->
        [<<"[">>, join([encode1(T) || T <- Term], <<",">>), <<"]">>]
    end.

join(Items, Sep) -> join1(Items, Sep, []).
join1([], _, Acc) -> lists:reverse(Acc);
join1([H], Sep, Acc) -> join1([], Sep, [H|Acc]);
join1([H|T], Sep, Acc) -> join1(T, Sep, [Sep,H|Acc]).

Note that this implementation allows some invalid JSON constructs, like keys that aren't strings.

Martin Törnwall
  • 9,299
  • 2
  • 28
  • 35