在erlang中将列表转换并格式化为字符串

时间:2016-07-07 11:39:04

标签: list erlang

我在erlang中有一个列表,我需要将其转换为查询字符串参数并通过http发送。通过http发送没有问题,但是querystring参数没有以我想要的方式格式化。我尝试了两件事:

Snippet 1

error_logger:info_msg("~p", [Mylist]),  %% ==> prints [<<"foo">>,<<"bar">>] 
Response = httpc:request("http://someserver/someaction?mylist=" ++ [Mylist]). 
%% ==> Server receives Mylist param as: 'foobar' but I want it to be 'foo/bar'

Snippet 2

error_logger:info_msg("~p", [Mylist]),  %% ==> prints [<<"foo">>,<<"bar">>] 
IOList = io_lib:format("~p", [Mylist]),
FlatList = lists:flatten([IOList]),
Response = httpc:request("http://someserver/someaction?mylist=" ++ [FlatList]).
%% ==> Server receives Mylist param as: '[<<"foo">>,<<"bar">>]' but I want it to be 'foo/bar'

有人可以帮我转换和格式化列表,我可以接收列表中带有'/'字符的所有项目

提前致谢

1 个答案:

答案 0 :(得分:4)

如果您希望在URL中的列表元素之间显示/字符,则必须将其放在那里。一种方法是使用lists:join/2

Response = httpc:request("http://someserver/someaction?mylist=" ++ lists:join("/", Mylist)).

这导致一个由字符串和二进制文件组成的iolist作为URL参数传递给httpc:request/1,这在我尝试时对我有用,但由于httpc documentation表示URL,因此严格地说不正确type是一个字符串。为此,您可以先在Mylist中转换二进制文件,然后展平连接的结果以获取字符串:

Value = lists:flatten(lists:join("/", [binary_to_list(B) || B <- Mylist])),
Response = httpc:request("http://someserver/someaction?mylist=" ++ Value).

编辑:请注意lists:join/2仅在Erlang / OTP 19.0或更新版本中可用;对于旧版本,您可以改为使用string:join/2,但请注意参数是相反的,即"/"分隔符必须是第二个参数,而不是第一个参数。

相关问题