File tree Expand file tree Collapse file tree 1 file changed +24
-13
lines changed Expand file tree Collapse file tree 1 file changed +24
-13
lines changed Original file line number Diff line number Diff line change @@ -24,28 +24,39 @@ Using [purescript-argonaut-core](https://github.com/purescript-contrib/purescrip
24
24
25
25
``` purescript
26
26
someObject =
27
- let
28
- objects =
27
+ let
28
+ objects =
29
29
[ jsonSingletonObject "bar" (fromString "a")
30
30
, jsonSingletonObject "bar" (fromString "b")
31
31
]
32
32
in
33
33
fromObject $ Object.fromFoldable [ Tuple "foo" (fromArray objects) ]
34
34
```
35
35
36
- The ` decodeJson ` and ` .? ` functions provided in this module make it straightforward to interrogate the ` Json ` object:
36
+ The ` decodeJson ` and ` .: ` functions provided in this module make it straightforward to interrogate the ` Json ` object:
37
37
38
38
``` purescript
39
- main =
40
- log $ show $ getBars someObject
41
-
42
- getBars :: Json -> Either String (Array String)
43
- getBars json = do
44
- obj <- decodeJson json
45
- foo <- obj .? "foo"
46
- for foo \itemJson -> do
47
- itemObj <- decodeJson itemJson
48
- itemObj .? "bar"
39
+ newtype MyType = MyType
40
+ { foo :: String
41
+ , bar :: Maybe Int
42
+ , baz :: Boolean
43
+ }
44
+
45
+ -- create a `DecodeJson` instance
46
+ instance decodeJsonMyType :: DecodeJson MyType where
47
+ decodeJson json = do
48
+ x <- decodeJson json
49
+ foo <- x .: "foo" -- mandatory field
50
+ bar <- x .:? "bar" -- optional field
51
+ baz <- x .:? "baz" .!= false -- optional field with default value of `false`
52
+ pure $ MyType { foo, bar, baz }
53
+
54
+ -- or pass a function
55
+ decodeMyTypes :: Json -> Either String (Array MyType)
56
+ decodeMyTypes json = do
57
+ x <- decodeJson json
58
+ arr <- x .: "myTypes"
59
+ for arr decodeJson
49
60
```
50
61
51
62
## Contributing
You can’t perform that action at this time.
0 commit comments