Skip to content

New Example #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 11, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 0 additions & 30 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,34 +24,4 @@ you need to define an instance for Encode.
If you have some JSON, and you want to decode it into some data type,
you need to define an instance for Decode.

## Examples

```purescript
module Foo where

import Control.Identity
import Data.Argonaut
import Data.Either

data Foo = Foo
{ foo :: String
, bar :: Number
}

instance showFoo :: Show Foo where
show (Foo f) = "Foo(" ++ show f.foo ++ ", " ++ show f.bar ++ ")"

instance decodeFoo :: DecodeJson Identity (Either String) Foo where
decodeJson (Identity json) = maybe (Left "Not a Foo.") Right $ do
obj <- toObject json
foo <- (M.lookup "foo" obj >>= toString)
bar <- (M.lookup "bar" obj >>= toNumber)
pure (Foo {foo: foo, bar: bar})

instance encodeFoo :: EncodeJson Identity Identity Foo where
encodeJson (Identity (Foo {foo = f, bar = b})) = Identity $ JsonObject $
M.fromList [Tuple "foo" $ JsonString f, Tuple "bar" $ JsonNumber b]
```

[508]: https://github.com/purescript/purescript/tree/508
[argonaut]: http://argonaut.io/
36 changes: 36 additions & 0 deletions examples/Examples/Data/Argonaut/Record.purs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
module Examples.Data.Argonaut.Record where

import Data.Argonaut ((~>), (:=), (.?), jsonEmptyObject, printJson)
import Data.Argonaut.Encode (EncodeJson, encodeJson)
import Data.Argonaut.Decode (DecodeJson, decodeJson)
import Data.Maybe (Maybe(..))

import Debug.Trace (print)

newtype Foo = Foo
{ foo :: Maybe Number
, bar :: Maybe String
}

instance decodeJsonFoo :: DecodeJson Foo where
decodeJson json = do
obj <- decodeJson json
foo <- obj .? "foo"
bar <- obj .? "bar"
pure $ Foo {foo: foo, bar: bar}

instance encodeJsonFoo :: EncodeJson Foo where
encodeJson (Foo f)
= "bar" := f.bar
~> "foo" := f.foo
~> jsonEmptyObject

instance showFoo :: Show Foo where
show (Foo f) = "Foo {foo: " ++ show f.foo ++ ", bar:" ++ show f.bar ++ "}"

foo :: Foo
foo = Foo {foo: Just 42, bar: Nothing}

main = do
print $ "raw foo is: " ++ show foo
print $ "encoded foo is: " ++ printJson (encodeJson foo)
Loading