Skip to content

Commit 5102aa3

Browse files
committed
Merge pull request #10 from joneshf/master
New Example
2 parents ce4cb29 + 54e1a9b commit 5102aa3

File tree

3 files changed

+478
-472
lines changed

3 files changed

+478
-472
lines changed

README.md

Lines changed: 0 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -24,34 +24,4 @@ you need to define an instance for Encode.
2424
If you have some JSON, and you want to decode it into some data type,
2525
you need to define an instance for Decode.
2626

27-
## Examples
28-
29-
```purescript
30-
module Foo where
31-
32-
import Control.Identity
33-
import Data.Argonaut
34-
import Data.Either
35-
36-
data Foo = Foo
37-
{ foo :: String
38-
, bar :: Number
39-
}
40-
41-
instance showFoo :: Show Foo where
42-
show (Foo f) = "Foo(" ++ show f.foo ++ ", " ++ show f.bar ++ ")"
43-
44-
instance decodeFoo :: DecodeJson Identity (Either String) Foo where
45-
decodeJson (Identity json) = maybe (Left "Not a Foo.") Right $ do
46-
obj <- toObject json
47-
foo <- (M.lookup "foo" obj >>= toString)
48-
bar <- (M.lookup "bar" obj >>= toNumber)
49-
pure (Foo {foo: foo, bar: bar})
50-
51-
instance encodeFoo :: EncodeJson Identity Identity Foo where
52-
encodeJson (Identity (Foo {foo = f, bar = b})) = Identity $ JsonObject $
53-
M.fromList [Tuple "foo" $ JsonString f, Tuple "bar" $ JsonNumber b]
54-
```
55-
56-
[508]: https://github.com/purescript/purescript/tree/508
5727
[argonaut]: http://argonaut.io/
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
module Examples.Data.Argonaut.Record where
2+
3+
import Data.Argonaut ((~>), (:=), (.?), jsonEmptyObject, printJson)
4+
import Data.Argonaut.Encode (EncodeJson, encodeJson)
5+
import Data.Argonaut.Decode (DecodeJson, decodeJson)
6+
import Data.Maybe (Maybe(..))
7+
8+
import Debug.Trace (print)
9+
10+
newtype Foo = Foo
11+
{ foo :: Maybe Number
12+
, bar :: Maybe String
13+
}
14+
15+
instance decodeJsonFoo :: DecodeJson Foo where
16+
decodeJson json = do
17+
obj <- decodeJson json
18+
foo <- obj .? "foo"
19+
bar <- obj .? "bar"
20+
pure $ Foo {foo: foo, bar: bar}
21+
22+
instance encodeJsonFoo :: EncodeJson Foo where
23+
encodeJson (Foo f)
24+
= "bar" := f.bar
25+
~> "foo" := f.foo
26+
~> jsonEmptyObject
27+
28+
instance showFoo :: Show Foo where
29+
show (Foo f) = "Foo {foo: " ++ show f.foo ++ ", bar:" ++ show f.bar ++ "}"
30+
31+
foo :: Foo
32+
foo = Foo {foo: Just 42, bar: Nothing}
33+
34+
main = do
35+
print $ "raw foo is: " ++ show foo
36+
print $ "encoded foo is: " ++ printJson (encodeJson foo)

0 commit comments

Comments
 (0)