Last active
December 17, 2015 06:49
-
-
Save reite/5568152 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
parseInvoices :: L.ByteString -> Either String [Invoice] | |
parseInvoices s = do | |
result <- eitherDecode s | |
flip parseEither result $ \obj -> do | |
d <- (obj .: "invoices") >>= (.: "invoice") | |
case d of | |
Object v -> return [v] | |
Array v -> return v |
Solution:
import qualified Data.Vector as V
parseObjOrArray :: (FromJSON a) => Value -> Parser a
parseObjOrArray obj = case obj of
ob@(Object v) -> parseJSON $ Array (V.singleton ob)
arr@(Array v) -> parseJSON arr
_ -> error "Expected {} or []"
Use like this:
parseInvoices :: L.ByteString -> Either String [Invoice]
parseInvoices s = do
result <- eitherDecode s
flip parseEither result $ \obj -> (obj .: "invoices") >>= (.: "invoice") >>= parseObjOrArray
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The structure of the json looks like this:
where "invoice" will be a Array of Objects if there are more than 1 entry, or a single Object if there is only one.