这行得通:
λ decode "[\"one\", \"two\"]" :: Maybe [Text]
Just ["one","two"]
这行得通:
λ decode "[1, 2]" :: Maybe [Int]
Just [1,2]
这是完全有效的 JSON,但我无法使其工作:
λ decode "[\"one\", 2]" :: Maybe [Text]
Nothing
甚至:
λ decode "[2]" :: Maybe [Text]
Nothing
我想说服最后一个给我:
Just ["one","2"]
Just ["2"]
但我无法看到将 Aeson 的 ARM 扭到看到它想将其视为数字的字符串。
更新:
λ decode "[1, \"2\"]" :: Maybe Array
Just (fromList [Number 1.0,String "2"])
我想这会好一些。我仍然希望我可以让 Aeson 将所有内容强制转换为字符串,但我想我可以解决这个问题。
最佳答案
Text
的标准 FromJSON
实例不会执行您正在寻找的那种强制。幸运的是,aeson
足够灵活,可以让您使用自己的规则定义自己的类型。这是一个例子,complete on FP Haskell Center .它的主要部分是:
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"
关于haskell - 让 Aeson 处理混合类型的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26515375/