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
2424
2525``` purescript
2626someObject =
27- let
28- objects =
27+ let
28+ objects =
2929 [ jsonSingletonObject "bar" (fromString "a")
3030 , jsonSingletonObject "bar" (fromString "b")
3131 ]
3232 in
3333 fromObject $ Object.fromFoldable [ Tuple "foo" (fromArray objects) ]
3434```
3535
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:
3737
3838``` 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
4960```
5061
5162## Contributing
You can’t perform that action at this time.
0 commit comments