2017-09-15 114 views
0

我試圖在我的請求中訪問內部Object。這是我的代碼:解析JSON haskell

{-# LANGUAGE OverloadedStrings #-} 


import Network.Wreq 
import Control.Lens 
import Data.Aeson 

import Data.Map as Map 

type Resp = Response (Map String Value) 


main = do 
    r <- asJSON =<< get "https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC" :: IO Resp 
    let result = (r ^. responseBody)  
    print result 

這是我的結果:

fromList [("message",String ""),("result",Object (fromList [("Bid",Number 1.441e-2),("Ask",Number 1.44101e-2),("Last",Number 1.441e-2)])),("success",Bool True)] 

我試圖訪問「結果」鍵的對象,然後訪問的還有裏面的值。我不知道該怎麼做,我搞砸了AESON和^?運營商,wreq提供,但它不適合我。

回答

4
{-# LANGUAGE OverloadedStrings #-} 

import Control.Lens 
import Network.Wreq 
import Data.Aeson.Lens 

import Data.HashMap.Lazy (HashMap) 
import Data.Text (Text) 

main = do 
    r <- asValue =<< get "https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC" 
    let result = 
     (r :: Response Value) 
      -- get the Value out of the Response 
      ^? responseBody 
      -- The Value must be an Object, then unwrap the contained (HashMap Text Value) 
      . _Object 
      -- In the map {"message": ..., "result": ...}, get the "result". 
      . ix "result" 
      -- This must be an Object, unwrap the (HashMap Text Value) 
      . _Object 
    print (result :: HashMap Text Value) 

-- How types line up: 
-- 
-- responseBody . _Object . ix "result" . _Object 
--   :: Traversal' (Response Value)         (HashMap Text Value) 

-- 
-- responseBody :: Lens' (Response Value) Value 
-- _Object  ::    Traversal' Value (HashMap Text Value) 
-- ix "result" ::     Traversal' (HashMap Text Value) Value 
-- _Object  ::          Traversal' Value (HashMap Text Value)