case a -6ren">
gpt4 book ai didi

json - 解析 JSON 中的嵌套值

转载 作者:行者123 更新时间:2023-12-04 23:52:27 24 4
gpt4 key购买 nike

我有这么丑陋的代码部分:

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/Aeson Traversals/Prisms提供了使用 lens 的示例解析 JSON
  • A Little Lens Starter Tutorial贯穿整个lens苏格拉底风格的包装。

  • 无论如何,对于您的特定示例,我们可以用类似的东西替换这个嵌套的案例
    print $ responseBody res ^!? key "aaa" 
    . key "bbb"
    . key "ccc"
    . ix 1
    . _String

    虽然我建议避免像 error 这样的事情表示失败。 (^?)组合器(也称为 preview )会有所帮助。

    关于json - 解析 JSON 中的嵌套值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473093/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com