我有这么丑陋的代码部分:
request <- parseUrl "someUrl.com"
res <- withManager $ httpLbs request
case decode $ responseBody res :: Maybe Aeson.Value of
Just (Aeson.Object jsonObject) ->
case (HashMap.lookup "aaa" jsonObject) of
Just a ->
case a of
Aeson.Object jsonObject2 ->
case (HashMap.lookup "bbb" jsonObject2) of
Just b ->
case b of
Aeson.Object jsonObject3 ->
case (HashMap.lookup "ccc" jsonObject3) of
Just c ->
case c of
Array d ->
case (d ! 1) of
String a -> print a
_ -> error "error!!!"
_ -> error "error!!"
_ -> error "error!!"
_ -> error "error!!"
_ -> error "error!!"
_ -> error "error!!"
_ -> error "error!!"
_ -> error "Invalid JSON"
它运行良好,但看起来不太好。我如何简化它?我很肯定有办法做到这一点。
请注意,我是 不是 使用任何自定义数据类型来解析 JSON 并且不想这样做。
最佳答案
这个问题——深入研究大型、复杂的数据结构,正是 lens
寻求解决。 Lens
的想法es 不难,但包 lens
可能很可怕。我已经写了一些关于这个概念的教程,但是,这可能很有用
lens
的示例解析 JSON lens
苏格拉底风格的包装。 无论如何,对于您的特定示例,我们可以用类似的东西替换这个嵌套的案例
print $ responseBody res ^!? key "aaa"
. key "bbb"
. key "ccc"
. ix 1
. _String
虽然我建议避免像
error
这样的事情表示失败。 (^?)
组合器(也称为 preview
)会有所帮助。
关于json - 解析 JSON 中的嵌套值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473093/