Skip to content

About

JSON decoders and encoders for Haskell, in the style of elm/json, built on json-parser.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

63 Commits

Folders and files

Repository files navigation

JSON Codec

JSON decoders and encoders for Haskell, in the style of elm/json, built on json-parser.

Go between Haskell values and JSON values of any shape. Decoders convert JSON values into Haskell values while encoders convert Haskell values back into JSON values.

Usage

This package is distributed through its Git repository rather than Hackage. Add a source-repository-package stanza to cabal.project to use it. Since Cabal doesn't automatically resolve Git-hosted transitive dependencies, you will need to add a stanza for each of those as well.

In cabal.project:

source-repository-package
  type: git
  location: https://github.com/dwayne/hs-json-codec.git
  [tag: <hash|tag|branch>]

source-repository-package
  type: git
  location: https://github.com/dwayne/hs-json-parser.git
  [tag: <hash|tag|branch>]

N.B. Omitting the tag tracks the default branch and sacrifices reproducibility.

In example.cabal:

build-depends:
  json-codec

Decoding

You can create decoders for your types by composing with other decoders.

{-# LANGUAGE OverloadedStrings #-}

import qualified Json.Decode as JD

import Data.Text (Text)
import Json.Decode (Decoder)

data User
  = User
      { name  :: Text
      , age   :: Int
      , email :: Maybe Text
      }
  deriving (Eq, Show)

userDecoder :: Decoder User
userDecoder =
  User
    <$> JD.field "name" JD.text
    <*> JD.field "age" JD.integral
    <*> JD.field "email" (JD.nullable JD.text)

A Decoder User knows how to convert a JSON value into a User, or describe why it could not.

To use a decoder you have to run it.

JD.decodeText userDecoder "{\"name\": \"Douglas\", \"age\": 71, \"email\": null}"
-- Right (User { name = "Douglas", age = 71, email = Nothing })

JD.decodeText userDecoder "{\"name\": \"Douglas\"}"
-- Left (DecodeError (FieldError "age" (Failure "missing key" ...)))

There are other runners besides decodeText. decodeValue runs a decoder on an already-parsed JSON value. Whereas, decodeFile reads a file, parses its contents as JSON, and runs the decoder on the result.

FromJson

FromJson names the canonical decoder for a type.

instance FromJson User where
  decoder = userDecoder

Or, alternatively:

instance FromJson User where
  decoder =
    User
      <$> field "name" decoder
      <*> field "age" decoder
      <*> field "email" decoder

Encoding

Encoders are functions from a Haskell value to a JSON value. You can create encoders for your types by composing with other encoders.

{-# LANGUAGE OverloadedStrings #-}

import qualified Json.Encode as JE

import Data.Text (Text)
import Json.Encode (Json)

data User
  = User
      { name  :: Text
      , age   :: Int
      , email :: Maybe Text
      }
  deriving (Eq, Show)

encodeUser :: User -> Json
encodeUser (User name age email) =
  JE.object
    [ ( "name", JE.text name )
    , ( "age", JE.int age )
    , ( "email", JE.nullable JE.text email )
    ]

You use an encoder like you would any other function.

encodeUser (User { name = "Douglas", age = 71, email = Nothing })
-- Object
--   [ ( "name", String "Douglas" )
--   , ( "age", Number (Num {numSign = Plus, numDigits = "71", numFraction = Nothing, numExponent = Nothing}) )
--   , ( "email", Null )
--   ]

encodeUser (User { name = "Douglas", age = 71, email = Just "douglas@crockford.com" })
-- Object
--   [ ( "name", String "Douglas" )
--   , ( "age", Number (Num {numSign = Plus, numDigits = "71", numFraction = Nothing, numExponent = Nothing}) )
--   , ( "email", String "douglas@crockford.com" )
--   ]

ToJson

ToJson names the canonical encoder for a type.

instance ToJson User where
  encode = encodeUser

Or, alternatively:

instance ToJson User where
  encode (User name age email) =
    JE.object
      [ ("name", JE.encode name)
      , ("age", JE.encode age)
      , ("email", JE.encode email)
      ]

Public API

Json.Decode

Json(..), Number, Sign(..), Array, and Object are re-exported from json-parser.

newtype Decoder a

instance Functor Decoder
instance Applicative Decoder
instance Monad Decoder

class FromJson a where
  decoder :: Decoder a

instance FromJson Bool
instance FromJson Int
instance FromJson Integer
instance FromJson Float
instance FromJson Double
instance FromJson Rational
instance FromJson Number
instance FromJson Text
instance FromJson Json
instance FromJson a => FromJson [a]
instance FromJson a => FromJson (Maybe a)
instance (FromJson a, FromJson b) => FromJson (a, b)
instance (FromJson a, FromJson b, FromJson c) => FromJson (a, b, c)
instance (FromJson a, FromJson b, FromJson c, FromJson d) => FromJson (a, b, c, d)
instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e) => FromJson (a, b, c, d, e)
instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f) => FromJson (a, b, c, d, e, f)
instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g) => FromJson (a, b, c, d, e, f, g)
instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g, FromJson h) => FromJson (a, b, c, d, e, f, g, h)

-- Primitives

succeed :: a -> Decoder a
fail :: Text -> Decoder a
json :: Decoder Json
null :: a -> Decoder a
bool :: Decoder Bool
text :: Decoder Text

-- Number Primitives

number :: Decoder Number
rational :: Decoder Rational
integral :: Integral a => Decoder a
boundedIntegral :: (Bounded a, Integral a) => Decoder a
fractional :: Fractional a => Decoder a

-- Array Primitives

list :: Decoder a -> Decoder [a]
index :: Int -> Decoder a -> Decoder a

-- Object Primitives

keyValuePairs :: Decoder v -> Decoder [(Text, v)]
keyValuePairsWithKeyTransformer :: (Text -> Either Text k) -> Decoder v -> Decoder [(k, v)]
field :: Text -> Decoder a -> Decoder a
at :: [Text] -> Decoder a -> Decoder a
optionalAt :: [Text] -> Decoder a -> Decoder (Maybe a)

-- Inconsistent Structure

nullable :: Decoder a -> Decoder (Maybe a)
maybe :: Decoder a -> Decoder (Maybe a)
oneOf :: [Decoder a] -> Decoder a

-- Run Decoders

decodeValue :: Decoder a -> Json -> Either DecodeError a
decodeText :: Decoder a -> Text -> Either Error a
decodeFile :: Decoder a -> FilePath -> IO (Either Error a)

-- Errors

data Error
  = EncodingError UnicodeException
  | SyntaxError SyntaxError
  | DecodeError DecodeError
  deriving (Eq, Show)

type SyntaxError = ParseErrorBundle Text Void

data DecodeError
  = Failure Text Json
  | ExpectedNull Json
  | ExpectedBoolean Json
  | ExpectedNumber Json
  | ExpectedString Json
  | ExpectedArray Json
  | ExpectedObject Json
  | IndexError Int DecodeError
  | FieldError Text DecodeError
  | OneOfError [DecodeError]
  deriving (Eq, Show)

Json.Encode

Json(..), Number, Sign(..), Array, and Object are re-exported from json-parser.

class ToJson a where
  encode :: a -> Json

instance ToJson Bool
instance ToJson Int
instance ToJson Integer
instance ToJson Float
instance ToJson Double
instance ToJson Number
instance ToJson Text
instance ToJson a => ToJson [a]
instance ToJson a => ToJson (Maybe a)

-- Basic

null :: Json
bool :: Bool -> Json

-- Number

int :: Int -> Json
integer :: Integer -> Json
float :: Float -> Json
double :: Double -> Json
number :: Number -> Json

-- String

text :: Text -> Json
string :: String -> Json

-- Array

array :: Array -> Json
list :: (a -> Json) -> [a] -> Json
list' :: ToJson a => [a] -> Json

-- Object

object :: Object -> Json
keyValuePairs :: (v -> Json) -> [(Text, v)] -> Json
keyValuePairs' :: ToJson v => [(Text, v)] -> Json
keyValuePairsWithKeyTransformer :: (k -> Text) -> (v -> Json) -> [(k, v)] -> Json
keyValuePairsWithKeyTransformer' :: ToJson v => (k -> Text) -> [(k, v)] -> Json

-- Inconsistent Structure

nullable :: (a -> Json) -> Maybe a -> Json
nullable' :: ToJson a => Maybe a -> Json

About

JSON decoders and encoders for Haskell, in the style of elm/json, built on json-parser.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Contributors

Languages