[erlang-questions] Maps and binaries

Loïc Hoguin essen@REDACTED
Wed Dec 12 11:29:50 CET 2018


Just match directly and let io:format convert for you:

#{<<"outputs">> := [_, #{
     <<"api">> := Api,
     <<"name">> := Dev
}|_]} = jsone:decode(Resp),
io:format("\"~s\", \"~s\"~n", [Api, Dev]).

Or ~ts if it can have Unicode characters.

On 12/12/18 11:24 AM, Bob Cowdery wrote:
> Hi,
> 
> Its a long time since using Erlang so just getting back in. I know that 
> there is always better ways to do things so is there a better patten 
> matching way than this straight forward step-wise method.
> I have output from a UDP request put through jstone:decode which ends up 
> like so:
> #{<<"outputs">> =>
>        [#{<<"api">> => <<"MME">>,<<"channels">> => 2,<<"direction">> => 1,
>           <<"index">> => 5,<<"name">> => <<"Microsoft Sound Mapper - 
> Output">>},
>         #{<<"api">> => <<"MME">>,<<"channels">> => 8,<<"direction">> => 1,
>           <<"index">> => 6,<<"name">> => <<"Speakers (Realtek High 
> Definiti">>},
> ...
>       #{<<"api">> => <<>>,<<"channels">> => 0,<<"direction">> => 0,
>           <<"index">> => 0,<<"name">> => <<>>}]}
> I want to extract the second member api and name.
> 
>      Map = jsone:decode(Resp),
>      List = maps:get(<<"outputs">>, Map),
>      Element = lists:nth(2, List),
>      Api = my_binary_to_list(maps:get(<<"api">>, Element)),
>      Dev = my_binary_to_list(maps:get(<<"name">>, Element)),
>      io:format("~p, ~p~n", [Api, Dev]).
> 
> my_binary_to_list(<<H,T/binary>>) ->
>      [H|my_binary_to_list(T)];
> my_binary_to_list(<<>>) -> [].
> 
> prints:
> 
> "MME", "Speakers (Realtek High Definiti"
> 
> Thanks in advance, Bob
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions

-- 
Loïc Hoguin
https://ninenines.eu



More information about the erlang-questions mailing list