Convert string tuple representation to real tuple

How to convert this string "[{type,a},{to,room01023123},{body,hey what up mister},{by,someone}]"to a tuple like this[{"type","a"},{"to","room01023123"},{"body","hey what up mister"},{"by","someone"}]

+3
source share
2 answers

If you need to read from a file, just use file:consult

-spec consult(Filename) -> {ok, Terms} | {error, Reason}

Otherwise, you can use the module erl_parsein conjunction with erl_scan. In the simplest case, such as

{ok, Tokens, _Line} = erl_scan:string("{hello, world}."),
erl_parse:parse_term(Tokens).

And do not forget that the terms should end with a full stop.

+5
source

Forehead Solution:

Str = "[{type,a},{to,room01023123},{body,hey what up mister},{by,someone}]".
Need = [{"type","a"},{"to","room01023123"},{"body","hey what up mister"},{"by","someone"}].
L1 = string:tokens(tl(Str),",").
R=[fun(El)->Add= case El==length(L1)-1 of true->2;false->1 end, 
 Temp = lists:nth(X+1,L1),
 {tl(lists:nth(X,L1)),lists:sublist(Temp,1,length(Temp)-Add)} end(X) 
||X<-lists:seq(1,length(L1),2)].
-1
source

Source: https://habr.com/ru/post/1608575/


All Articles