Reputation: 151
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??
Upvotes: 0
Views: 1531
Reputation: 918
>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.
Upvotes: 0
Reputation: 9599
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.
Upvotes: -1
Reputation: 26121
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.
Upvotes: 4
Reputation: 511
You can convert Temp via http://erlang.org/doc/man/erlang.html#list_to_binary-1
And then do the same.
Upvotes: -1