[erlang-questions] Maps and binaries

Bob Cowdery bob@REDACTED
Wed Dec 12 11:24:35 CET 2018


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



More information about the erlang-questions mailing list