我正在通过解决一些在线练习问题来熟悉一些Haskell库。
我有一些代码,输出如下:
Object (fromList [("ABC", String "123")])
它也可能是
Object (fromList [("123", String "ABC")])
Object (fromList [(String "123", String "ABC")])
Object (fromList [("123", "ABC")])
我需要提取的是"123"
使用类型为(.:) :: FromJSON a => Object -> Text -> Parser a
的.:
函数来提取给定键的值会导致此错误
• Couldn't match type ‘Value’ with ‘HashMap Text Value’
Expected type: Object
Actual type: Value
我的最佳猜测是我需要编写一个解析器,但我不知道如何着手做或者该寻找什么。
产生错误的代码:
x <- (eitherDecode <$> simpleHttp url) :: IO (Either String DataSet)
case x of
Left er -> print er
Right an -> do
let l = S.toList (data1 an)
print $ l .: "ABC"
DataSet的定义如下:
newtype DataSet = DataSet {
data1 :: Object
} deriving (Show, Generic)
如果我要替换
print $ (Data.List.head l) .: "ABC"
只需要
print $ (Data.List.head l)
我理解为
Object (fromList [("ABC", String "123")])
let l = L.toList (data1 an)
而不是let l = data1 an
?这似乎可能是问题所在。 - AJFdata1 an
输出的是一个Object
类型。an
包含许多Object (fromList [("ABC", "123")])
。对其应用toList
可以将其转换为列表并逐个提取出每个元素。 - atisl
仍然是一个列表,而你正在编写l .: "ABC"
,这不是良好类型化的,那么你为什么要写那个呢? - AJF