Getting Aeson to work with a mixed list type
It works:
λ decode "[\"one\", \"two\"]" :: Maybe [Text]
Just ["one","two"]
It works:
λ decode "[1, 2]" :: Maybe [Int]
Just [1,2]
This is perfectly valid JSON, but I cannot get it to work:
λ decode "[\"one\", 2]" :: Maybe [Text]
Nothing
Or even:
λ decode "[2]" :: Maybe [Text]
Nothing
I would like to convince the latter to give me:
Just ["one","2"]
Just ["2"]
But I don't see how to flip Ezon's hand after seeing something that she wants to see as a number as a string.
Update:
λ decode "[1, \"2\"]" :: Maybe Array
Just (fromList [Number 1.0,String "2"])
I think this is a little better. I still wish I could get Ezon to force everything to the strings, but I think I can handle it.
+3
source to share
1 answer
Standard FromJSON
copy for Text
won't do the kind of compulsion you're looking for. Fortunately, it's aeson
flexible enough that you can define your own types with your own rules. Here's an example at the FP Haskell Center . Its main part:
newtype LaxText = LaxText Text
deriving Show
instance FromJSON LaxText where
parseJSON (String t) = return $ LaxText t
parseJSON (Number n) = return $ LaxText $ toStrict $ toLazyText $ scientificBuilder n
parseJSON _ = fail "Invalid LaxText"
+7
source to share