jsonerlangmochijson2

Erlang : JSON List to JSON List


I have a list of JSON objects (received from a nosql db) and want to remove or rename some keys. And then I want to return data as a list of JSON objects once again.

This Stackoverflow post provides a good sense of how to use mochijson2. And I'm thinking I could use a list comprehension to go through the list of JSON objects.

The part I am stuck with is how to remove the key for each JSON object (or proplist if mochijson2 is used) within a list comprehension. I can use the delete function of proplists. But I am unsuccessful when trying to do that within a list comprehension.

Here is a bit code for context :

A = <<"[{\"id\": \"0129\", \"name\": \"joe\", \"photo\": \"joe.jpg\"  }, {\"id\": \"0759\", \"name\": \"jane\", \"photo\": \"jane.jpg\"  }, {\"id\": \"0929\", \"name\": \"john\", \"photo\": \"john.jpg\" }]">>. 
Struct = mochijson2:decode(A). 
{struct, JsonData} = Struct,
{struct, Id} = proplists:get_value(<<"id">>, JsonData),

Any suggestions illustrated with code much appreciated.


Solution

  • You can use lists:keydelete(Key, N, TupleList) to return a new tuple list with certain tuples removed. So in the list comprehension, for each entry extract the tuple lists (or proplists), and create a new struct with the key removed:

    B = [{struct, lists:keydelete(<<"name">>, 1, Props)} || {struct, Props} <- Struct].
    

    gives:

    [{struct,[{<<"id">>,<<"0129">>},
              {<<"photo">>,<<"joe.jpg">>}]},
     {struct,[{<<"id">>,<<"0759">>},
              {<<"photo">>,<<"jane.jpg">>}]},
     {struct,[{<<"id">>,<<"0929">>},
              {<<"photo">>,<<"john.jpg">>}]}]
    

    and

    iolist_to_binary(mochijson2:encode(B)).
    

    gives:

    <<"[{\"id\":\"0129\",\"photo\":\"joe.jpg\"},{\"id\":\"0759\",\"photo\":\"jane.jpg\"},{\"id\":\"0929\",\"photo\":\"john.jpg\"}]">>
    

    By the way, using the lists/* tuple lists functions are much faster, but sometimes slightly less convenient than the proplists/* functions: http://sergioveiga.com/index.php/2010/05/14/erlang-listskeyfind-vs-proplistsget_value/