如何元组的列表转换为二进制在二郎山 [英] How to convert list of tuples to binary in erlang
本文介绍了如何元组的列表转换为二进制在二郎山的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有
Message = [{"from_email",From_Email},{"name",Name},{"text",Text}],
To=[{"to_email",ToMail},{"to_name",ToName}],
Send_Mail=[{"to",To},{"subject",Subject},{"message",Message},{"from_email",From_Email},{"from_name",From_Name}].
我要Send_Mail转换成二进制解析成杰森格式。我使用JSX解析和JSX采用二进制输入。
I want to convert Send_Mail into binary to parse into jason format. I am using jsx for parsing and jsx takes binary inputs.
推荐答案
一个快速强力的方法:遍历列表,递归进入元组和列表,将所有串状列表,以二进制
A quick brute-force approach: iterate the list, recursively entering tuples and lists, converting all string-like lists to binary.
%% First exclude things that should be left alone:
list_to_jsx(E) when is_integer(E); is_float(E); is_atom(E); is_binary(E) -> E;
%% If converting a list, see if it can be made neatly into a
%% binary, if so, done, if not recurse into the list.
list_to_jsx(L) when is_list(L) ->
case catch list_to_binary(L) of
B when is_binary(B) -> B;
_ -> [convert(E) || E <- L]
end;
%% If converting a tuple, convert each element:
list_to_jsx(T) when is_tuple(T) ->
list_to_tuple([convert(E) || E <- tuple_to_list(T)]).
如果您确信只有2元组出现在输入列表中,最后一个子句可以稍微简化为
If you are confident that only 2-tuples appear in the input list, the last clause can be simplified slightly to
list_to_jsx({F,V}) -> {convert(F),convert(V)}.
这篇关于如何元组的列表转换为二进制在二郎山的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文