forked from devinus/jsonerl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
README
97 lines (64 loc) · 2.98 KB
/
README
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
It is modified version on Bob Ippolito's <bob@mochimedia.com> mochijson2 module, one can find in excellent mochiweb, erlang webserver.
Yet another JSON (RFC 4627) library for Erlang. jsonerl works with binaries as strings, arrays as lists (without an {array, _}) wrapper and it only knows how to decode UTF-8 (and ASCII).
It has the following mapping:
Erlang data type: => JavaScript data type: => Erlang data type:
-----------------------------------------------------------------------------------------------
1. atom true boolean true atom true
2. atom false boolean false atom false
3. atom undefined null atom undefined
4. any other atom string binary holding string
5. list array list
6. number number number
7. binary string binary
8. proptuple object proptuple
-----------------------------------------------------------------------------------------------
Note: proptuple is result of passing proplist to list_to_atom bif ;)
This is concept of mine to nicely model javascript object without a need of tagging structures on erlang side.
Eg. JavaScript object
{
name: "Luc Besson",
year_of_birth: 1959,
city: "Paris",
photo: "http://is.gd/3pYJF",
movies: ["Taken","Bandidas","Taxi"]
}
results in
{
{<<"name">>, <<"Luc Besson">>},
{<<"year_of_birth">>, 1959},
{<<"city">>, <<"Paris">>},
{<<"photo">>, <<"http://is.gd/3pYJF">>},
{<<"movies">>, [<<"Taken">>,<<"Bandidas">>,<<"Taxi">>]}
}
-----------------------------------------------------------------------------------------------
Additionally there is utility macros delivered with jsonerl that helps turning erlang records to json and back.
For example:
-include("jsonerl.hrl").
-record(artist, {name, year_of_birth, city, photo, movies}).
Artist = #artist{name = <<"Luc Besson">>, year_of_birth = 1959, city = <<"Paris">>, photo = <<"http://is.gd/3pYJF">>, movies = [<<"Taken">>,<<"Bandidas">>,<<"Taxi">>]},
Json = ?record_to_json(artist, Artist),
Artist = ?json_to_record(artist, Json).
the resulting json will be:
{
name: "Luc Besson",
year_of_birth: 1959,
city: "Paris",
photo: "http://is.gd/3pYJF",
movies: ["Taken","Bandidas","Taxi"]
}
-record(man,{name,age}).
Man1 = #man{name = "Petr", age = 45},
Man2 = #man{name = "Elton", age = 27 },
ListOfMans = [Man1,Man2],
ListJson = ?list_record_to_json(man,ListOfMans)
the resulting json will be:
[
{
name:"Petr",
age:45
},
{
name:"Elton",
age:27
}
]