aeson-extra-0.3.1.1: Extra goodies for aeson

Copyright(C) 2015-2016 Oleg Grenrus
LicenseBSD3
MaintainerOleg Grenrus <oleg.grenrus@iki.fi>
Safe HaskellNone
LanguageHaskell2010

Data.Aeson.Extra.CollapsedList

Description

 

Synopsis

Documentation

newtype CollapsedList f a Source

Collapsed list, singleton is represented as the value itself in JSON encoding.

λ > decode "null" :: Maybe (CollapsedList [Int] Int)
Just (CollapsedList [])
λ > decode "42" :: Maybe (CollapsedList [Int] Int)
Just (CollapsedList [42])
λ > decode "[1, 2, 3]" :: Maybe (CollapsedList [Int] Int)
Just (CollapsedList [1,2,3])
λ > encode (CollapsedList ([] :: [Int]))
"null"
λ > encode (CollapsedList ([42] :: [Int]))
"42"
λ > encode (CollapsedList ([1, 2, 3] :: [Int]))
"[1,2,3]"

Documentation rely on f Alternative instance behaving like lists'.

Constructors

CollapsedList (f a) 

parseCollapsedList :: (FromJSON a, FromJSON (f a), Alternative f) => Object -> Text -> Parser (f a) Source

Parses possibly collapsed array value from the object's field.

λ > newtype V = V [Int] deriving (Show)
λ > instance FromJSON V where parseJSON = withObject "V" $ \obj -> V <$> parseCollapsedList obj "value"
λ > decode "{}" :: Maybe V
Just (V [])
λ > decode "{\"value\": null}" :: Maybe V
Just (V [])
λ > decode "{\"value\": 42}" :: Maybe V
Just (V [42])
λ > decode "{\"value\": [1, 2, 3, 4]}" :: Maybe V
Just (V [1,2,3,4])