Skip to content

Examples

Eric Pailleau edited this page Jan 19, 2018 · 20 revisions

Examples

Encode and Decode records at runtime

Convert JSON object to record specification

Create a record definition file from a JSON sample :

1> A = jason:decode_file("priv/ex1.json",[{mode, record}, {to, "/tmp/records.hrl"}]).
{'22207878',{'34707836',"example glossary",
                            {'6257036',"S",
                                       {'131402670',{'49933946',"SGML","SGML",
                                                                "Standard Generalized Markup Language","SGML",
                                                                "ISO 8879:1986",
                                                                {'111785629',"A meta-markup language, used to create markup languages such as DocBook.",
                                                                             ["GML","XML"]},
                                                                "markup"}}}}}

Looking at content of record definition file :

$ cat /tmp/records.hrl
-record('111785629', {para  = []  :: list(), 'GlossSeeAlso'  = []  :: list()}).
-record('49933946', {'ID'  = []  :: list(), 'SortAs'  = []  :: list(), 'GlossTerm'  = []  :: list(), 'Acronym'  = []  :: list(), 'Abbrev'  = []  :: list(), 'GlossDef'  = '111785629':new()  :: '111785629':'111785629'(), 'GlossSee'  = []  :: list()}).
-record('131402670', {'GlossEntry'  = '49933946':new()  :: '49933946':'49933946'()}).
-record('6257036', {title  = []  :: list(), 'GlossList'  = '131402670':new()  :: '131402670':'131402670'()}).
-record('34707836', {title  = []  :: list(), 'GlossDiv'  = '6257036':new()  :: '6257036':'6257036'()}).
-record('22207878', {glossary  = '34707836':new()  :: '34707836':'34707836'()}).

Now edit a sample module :

-module(test).

-include("/tmp/records.hrl").

-export([test/1]).

test(File) -> A = jason:decode_file(File, [{mode, record}]),
              io:format("~p~n", [A#'22207878'.glossary#'34707836'.'GlossDiv'#'6257036'.'GlossList'#'131402670'.'GlossEntry'#'49933946'.'GlossTerm']).

Compile and test module :

1> c(test).
{ok,test}
2> test:test("git/jason/priv/ex1.json").
"Standard Generalized Markup Language"
ok

JSON to records translation when source is not stable

Clone this wiki locally