簡體   English   中英

在JSON中解析嵌套值

[英]Parsing nested values in JSON

我有一個如此丑陋的代碼部分:

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可能很嚇人。 我寫過一些關於這個概念的教程,但這可能很有用

在任何情況下,對於您的特定示例,我們可以用類似的東西替換這個嵌套的情況

print $ responseBody res ^!? key "aaa" 
                         .   key "bbb"
                         .   key "ccc"
                         .   ix 1 
                         .   _String

雖然我建議避免像error這樣的事情來表示失敗。 (^?)組合子(也稱為preview )會有所幫助。

Maybe monad do語法:

request <- parseUrl "someUrl.com"
res <- withManager $ httpLbs request
let toPrint =
  do Aeson.Object jsonObject <- decode $ responsBody res
     Aeson.Object jsonObject2 <- HashMap.lookup "aaa" jsonObject
     Aeson.Object jsonObject3 <- HashMap.lookup "bbb" jsonObject2
     Array d <- HashMap.lookup "ccc" jsonObject3
     String a <- return $ d ! 1
     return a
case toPrint of
    Just a -> print a
    Nothing -> "Invalid JSON"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM