Erlang : JSON List to JSON List -


i have list of json objects (received nosql db) , want remove or rename keys. , want return data list of json objects once again.

this stackoverflow post provides sense of how use mochijson2. , i'm thinking use list comprehension go through list of json objects.

the part stuck how remove key each json object (or proplist if mochijson2 used) within list comprehension. can use delete function of proplists. unsuccessful when trying within list comprehension.

here bit code 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 code appreciated.

you can use lists:keydelete(key, n, tuplelist) return new tuple list tuples removed. in list comprehension, each entry extract tuple lists (or proplists), , create new struct 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 way, using lists/* tuple lists functions faster, less convenient proplists/* functions: http://sergioveiga.com/index.php/2010/05/14/erlang-listskeyfind-vs-proplistsget_value/


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -