PrajaktaPurohit / ej

Helper module for working with Erlang terms representing JSON

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ej helps you work with Erlang terms representing JSON

The ej module is intended to make it easier to work with Erlang terms representing JSON as returned by mochijson2. You can use ej:get/2 to walk an object and return a particular value, ej:set/3 to update a value within an object, or ej:delete/2 to remove a value an object.

ej is best explained by example. Consider the following JSON data (borrowed from http://www.json.org/example.html):

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

mochijson2:decode/1 translates the JSON into Erlang terms like this:

{struct,
 [{<<"menu">>,
   {struct,
    [{<<"id">>,<<"file">>},
     {<<"value">>,<<"File">>},
     {<<"popup">>,
      {struct,
       [{<<"menuitem">>,
         [{struct,[{<<"value">>,<<"New">>},
                   {<<"onclick">>,<<"CreateNewDoc()">>}]},
          {struct,[{<<"value">>,<<"Open">>},
                   {<<"onclick">>,<<"OpenDoc()">>}]},
          {struct,[{<<"value">>,<<"Close">>},
                   {<<"onclick">>,<<"CloseDoc()">>}]}]}]}}]}}]}

And here’s ej in action:

% specify the path you want to access as a tuple of keys
4> ej:get({"menu", "value"}, Obj).
<<"File">>

% you can access list elements by index
> ej:get({"menu", "popup", "menuitem", 2, "onclick"}, Obj).
<<"OpenDoc()">>

% The atoms 'first' and 'last' can be used for lists as well
> ej:get({"menu", "popup", "menuitem", first, "value"}, Obj).  
<<"New">>

% set a value
Obj2 = ej:set({"menu", "id"}, Obj, <<"abc123">>).

% add a value
Obj3 = ej:set({"menu", "new_key"}, Obj, <<"something">>).

% add a value to a list
NewItem = {struct,[{<<"value">>,<<"Save">>}, {<<"onclick">>,<<"SaveDoc()">>}]}.
Obj4 = ej:set({"menu", "popup", "menuitem", new}, Obj, NewItem).

The idea for this helper module was inspired by this thread on the Erlang Questions mailing list and, in particular, by the reply from Richard O’Keefe. Additional motivation from the very similar helper module struct included in the sticky notes example application from the folks at BeeBole.

THANKS

  • Christopher Brown
  • Christopher Maier
  • John Keiser

About

Helper module for working with Erlang terms representing JSON


Languages

Language:Erlang 100.0%