How To equal <<"xxxasdew">> , and '<<"xxxasdew">>' in erlang

144 views Asked by At

I am having Data like the below:

Data = [{<<"status">>,<<"success">>},
       {<<"META">>,
       {struct,[{<<"createdat">>,1406895903.0},
       {<<"user_email">>,<<"[email protected]">>},
       {<<"campaign">>,<<"5IVUPHE42HP1NEYvKb7qSvpX2Cm">>}]}},
       {<<"mode">>,1}]

And Now i am having a

FieldList = ['<<"5IVUPHE42HP1NEYvKb7qSvpX2Cm">>']

Now:

I am trying like the below but i am getting empty instead of the value

90> [L || L <- FieldList,proplists:get_value(<<"campaign">>,element(2,proplists:get_value(<<"META">>,Data,{[],[]}))) == L].
[]

so how to get the both values are equal and get the final value.

3

There are 3 answers

2
filmor On

You can parse the atom as if it were an Erlang term:

atom_to_binary(Atom) ->
    L = atom_to_list(Atom),
    {ok, Tokens, _} = erl_scan:string(L ++ "."),
    {ok, Result} = erl_parse:parse_term(Tokens),
    Result.

You can then do

[L ||
   L <- FieldList,
   proplists:get_value(<<"campaign">>,
       element(2,
           proplists:get_value(<<"META">>,Data,{[],[]})))
   == atom_to_binary(L)
].

You can also do it the other way round, (trying to) convert the binary to an atom using this function:

binary_literal_to_atom(Binary) ->
    Literal = lists:flatten(io_lib:format("~p", [Binary])),
    try
        list_to_existing_atom(Literal)
    catch
        error:badarg -> undefined
    end.

This function will return undefined if the atom is not known yet (s. Erlang: binary_to_atom filling up atom table space security issue for more information on this). This is fine here, since the match can only work if the atom was known before, in this case by being defined in the FieldList variable.

How did you get those values in the first place?

0
Pascal On
Data = [{<<"status">>,<<"success">>},
        {<<"META">>,
            {struct,[{<<"createdat">>,1406895903.0},
                     {<<"user_email">>,<<"[email protected]">>},
                     {<<"campaign">>,<<"5IVUPHE42HP1NEYvKb7qSvpX2Cm">>}]
            }
         },
         {<<"mode">>,1}].

[_,{_,{struct,InData}}|_] = Data.

[X || {<<"campaign">>,X} <- InData].

it gives you the result in the form : [<<"5IVUPHE42HP1NEYvKb7qSvpX2Cm">>]

of course you can use the same kind of code if the tuple {struct,InData} may be in a different place in the Data variable.

0
BlackMamba On
-module(wy).
-compile(export_all).

main() ->
    Data = [{<<"status">>,<<"success">>},
        {<<"META">>,
         {struct,[{<<"createdat">>,1406895903.0},
              {<<"user_email">>,<<"[email protected]">>},
              {<<"campaign">>,<<"5IVUPHE42HP1NEYvKb7qSvpX2Cm">>}]
         }
        },
        {<<"mode">>,1}],
    Fun = fun({<<"META">>, {struct, InData}}, Acc) ->
          Value =  proplists:get_value(<<"campaign">>, InData, []),
          [Value | Acc];
         (_Other, Acc)->
          Acc
      end,
    lists:foldl(Fun, [], Data).

I think you can use this code.