GaloisInc / json

Haskell JSON library
Other
27 stars 10 forks source link

Add JSON Text instance for (de)serializing Text strings #1

Closed nurpax closed 11 years ago

nurpax commented 11 years ago

Add a Data.Text JSON instance to make it possible to serialize and deserialize data types containing Data.Text strings.

Currently only Strings are supported which makes it cumbersome to use Data.Text strings together with the json library.

This change adds a dependency to the 'text' library which is nowadays considered stable & the de facto way to work with unicode strings.

Example usage:


import Control.Applicative
import Text.JSON
import qualified Data.Text as T

data Foo = Foo T.Text
           deriving (Show)

instance JSON Foo where
  readJSON object = do
    obj <- readJSON object
    Foo <$> valFromObj "foo" obj

  showJSON (Foo s) =
    makeObj [("foo", showJSON s)]

test1 = "[{ \"foo\": \"bar\" }]"

parseFoo :: String -> [Foo]
parseFoo s = either (const []) id (resultToEither . decode $ s)

main :: IO ()
main = do
  putStrLn $ encode (Foo (T.pack "jope"))
  print $ parseFoo test1

Outputs:

nurpax@nurpax:~/dev/json-dev$ ./dist/build/jsontest/jsontest
{"foo":"jope"}
[Foo "bar"]
yav commented 11 years ago

Thanks for the patch!