Skip to content

Instantly share code, notes, and snippets.

@neongreen
Created March 31, 2018 14:28
Show Gist options
  • Save neongreen/ca4cb3c9e1b46cf963d48837d98660e8 to your computer and use it in GitHub Desktop.
Save neongreen/ca4cb3c9e1b46cf963d48837d98660e8 to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
import SuperRecord
import Data.Aeson
import Data.ByteString (ByteString)
main = do
print $ decodeIntsNewtype sample
print $ decodeIntsRecord sample
sample :: ByteString
sample = "{\"ints\": [1,2,3]}"
-----------------------------------------------------------
-- With a newtype
-----------------------------------------------------------
newtype Ints = Ints {ints :: [Int]}
instance FromJSON Ints where
parseJSON = withObject "ints" $ \o ->
Ints <$> o .: "ints"
decodeIntsNewtype :: ByteString -> Maybe [Int]
decodeIntsNewtype =
fmap ints .
decodeStrict
-----------------------------------------------------------
-- With a record
-----------------------------------------------------------
decodeIntsRecord :: ByteString -> Maybe [Int]
decodeIntsRecord =
fmap (get #ints) .
decodeStrict @(Rec '["ints" := [Int]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment