-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonEncoding.elm
executable file
·84 lines (68 loc) · 1.74 KB
/
JsonEncoding.elm
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
module JsonEncoding exposing (main, energyToString)
import Html exposing (Html)
import View exposing (triptych, meterList, code)
import Types exposing (Meter, Location, Energy(..))
import Json.Encode
main : Html a
main =
triptych "Let's encode some JSON!"
( "From", meterList meters )
( "We want to produce", code example )
( "Our work", code (encodeMeters meters) )
"/JsonDecoding.elm"
"Now the other way"
[]
meters : List Meter
meters =
[ Meter 1 True El (Location "CNGroup" "050")
, Meter 2 False Wa (Location "CNGroup" "070")
]
example : String
example =
"""[
{
"id": 1,
"automatic": true,
"energy": "el",
"location": {
"building": "CNGroup",
"room": "050"
}
},
{
"id": 2,
"automatic": false,
"energy": "wa",
"location": {
"building": "CNGroup",
"room": "070"
}
}
]"""
encodeMeters : List Meter -> String
encodeMeters meters =
meters
|> List.map encodeMeter
|> Json.Encode.list
|> Json.Encode.encode 2
encodeMeter : Meter -> Json.Encode.Value
encodeMeter meter =
Json.Encode.object
[ ( "id", Json.Encode.int meter.id )
, ( "automatic", Json.Encode.bool meter.automatic )
, ( "energy", Json.Encode.string (energyToString meter.energy) )
, ( "location", encodeLocation meter.location )
]
encodeLocation : Location -> Json.Encode.Value
encodeLocation location =
Json.Encode.object
[ ( "building", Json.Encode.string location.building )
, ( "room", Json.Encode.string location.room )
]
energyToString : Energy -> String
energyToString energy =
case energy of
El ->
"el"
Wa ->
"wa"