有没有什么好方法可以将列表/元组中的字符串转换为二进制数据? 例如:
输入:
[{"start", [{"data", [{"number",[{"@id","333"},{"#text","test message"}]}, {"data","current date"}]}, {"mass", [{"client","35"}, {"address","lattitude"}, {"code","3454343"}, {"foo",[{"@tipo","casa"},{"#text","Some text message 2"}]}, {"product","TEST"}]}]}]
输出:
[{<<"start">>, [{<<"data">>, [{<<"number">>,[{<<"@id">>,<<"333">>},{<<"#text">>,<<"test message">>}]}, {<<"data">>,<<"current date">>}]}, {<<"mass">>, [{<<"client">>,<<"35">>}, {<<"address">>,<<"lattitude">>}, {<<"code">>,<<"3454343">>}, {<<"foo">>,[{<<"@tipo">>,<<"casa">>},{<<"#text">>,<<"Some text message 2">>}]}, {<<"product">>,<<"TEST">>}]}]}]
像这样的东西
[list_to_binary(X) || X <- ["1","2","3"]].
但在另一个列表和元组中
我有一个我可以转换为JSON的proplist,但是JSX只接受二进制文件的问题。
答案 0 :(得分:3)
使用:
-module(test).
-compile(export_all).
to_binary({Term1, Term2}) ->
{to_binary(Term1), to_binary(Term2)};
to_binary([{_Term1, _Term2}|_Objs]=Terms) ->
[to_binary(Term) || Term <- Terms];
to_binary(Term) when erlang:is_list(Term) ->
erlang:list_to_binary(Term);
to_binary(Term) when erlang:is_number(Term) ->
Term;
to_binary(true) ->
true;
to_binary(false) ->
false;
to_binary(Term) when erlang:is_atom(Term) ->
erlang:list_to_binary(erlang:atom_to_list(Term));
to_binary(Term) ->
Term.
我使用你的输入运行上面的函数:
p@Jahanbakhsh ~/Projects/Test $ erl
Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V8.2.2 (abort with ^G)
1> c(test).
{ok,test}
2> Input = [{"start", [{"data", [{"number",[{"@id","333"},{"#text","test message"}]}, {"data","current date"}]}, {"mass", [{"client","35"}, {"address","lattitude"}, {"code","3454343"}, {"foo",[{"@tipo","casa"},{"#text","Some text message 2"}]}, {"product","TEST"}]}]}].
[{"start",
[{"data",
[{"number",[{"@id","333"},{"#text","test message"}]},
{"data","current date"}]},
{"mass",
[{"client","35"},
{"address","lattitude"},
{"code","3454343"},
{"foo",[{"@tipo","casa"},{"#text","Some text message 2"}]},
{"product","TEST"}]}]}]
3> test:to_binary(Input).
[{<<"start">>,
[{<<"data">>,
[{<<"number">>,
[{<<"@id">>,<<"333">>},{<<"#text">>,<<"test message">>}]},
{<<"data">>,<<"current date">>}]},
{<<"mass">>,
[{<<"client">>,<<"35">>},
{<<"address">>,<<"lattitude">>},
{<<"code">>,<<"3454343">>},
{<<"foo">>,
[{<<"@tipo">>,<<"casa">>},
{<<"#text">>,<<"Some text message 2">>}]},
{<<"product">>,<<"TEST">>}]}]}]
4>