Last active
July 30, 2019 16:43
-
-
Save pwm/0e50956420d4ceb38b813acc2584e007 to your computer and use it in GitHub Desktop.
Parse a substructure from json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE OverloadedStrings #-} | |
{-# LANGUAGE StrictData #-} | |
{-# LANGUAGE RecordWildCards #-} | |
{-# LANGUAGE DeriveGeneric #-} | |
{-# LANGUAGE DeriveAnyClass #-} | |
module ParseFoo where | |
import qualified Data.Text.Lazy.IO as T | |
import qualified Data.Text.Lazy.Encoding as T | |
import qualified Data.ByteString.Lazy.Internal as B | |
import qualified Data.Aeson as JSON | |
import qualified Data.Aeson.Encode.Pretty as JSON | |
import qualified Data.HashMap.Strict as HM | |
import qualified Data.Vector as V | |
import GHC.Generics | |
import Data.Aeson.Types | |
newtype Foo = MkFoo | |
{ _data :: (String, String) | |
} deriving (Eq, Show, Generic, ToJSON) | |
instance FromJSON Foo where | |
parseJSON = withObject "foo" $ \o -> do | |
_data <- head . HM.toList . V.head <$> o .: "results" | |
return MkFoo{..} | |
run :: IO () | |
run = do | |
bs <- T.encodeUtf8 <$> T.getLine | |
case parseFoo bs of | |
Just foo -> T.putStrLn $ T.decodeUtf8 $ JSON.encodePretty foo | |
_ -> T.putStrLn "{\"error\": \"bad input\"}" | |
where | |
parseFoo :: B.ByteString -> Maybe Foo | |
parseFoo bs = case JSON.decode bs of | |
Just v -> parseMaybe parseJSON v | |
_ -> Nothing | |
{- | |
usage: | |
λ> run | |
{"status":"ok","results":[{"k1":"v1"},{"k2":"v2"},{"k3":"v3"}]} | |
{ | |
"_data": [ | |
"k1", | |
"v1" | |
] | |
} | |
(12.23 secs, 488,000 bytes) | |
-} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment