我正在尝试在Haskell中学习Aeson库。 现在,我正在尝试解析一个简单的JSON文件
{
"Meta Data": {
"1: Symbol": "MSFT",
"2: Indicator": "Relative Strength Index (RSI)",
"3: Last Refreshed": "2018-10-15",
"4: Interval": "weekly",
"5: Time Period": 10,
"6: Series Type": "open",
"7: Time Zone": "US/Eastern Time"
},
"Technical Analysis: RSI": {
"2018-10-15": {
"RSI": "54.5653"
},
"2018-10-12": {
"RSI": "63.0279"
},
"2018-10-05": {
"RSI": "74.7519"
},
"2018-09-28": {
"RSI": "72.1573"
},
"2018-09-21": {
"RSI": "74.8123"
},
"2018-09-14": {
"RSI": "66.7116"
},
"2018-09-07": {
"RSI": "75.8051"
},
..and so on
在有关Aeson Aeson: the tutorial的本教程的帮助下 特别是“嵌套记录”部分
这是我到目前为止所掌握的。
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Tesst where
import Data.Aeson
import qualified Data.ByteString.Lazy as B
import Data.Time
import GHC.Exts
import GHC.Generics
import Network.HTTP.Conduit (simpleHttp)
data TechinicalAnalysis = TechinicalAnalysis {
name :: String,
date :: String,
rsi :: String
} deriving (Show, Generic)
instance FromJSON TechinicalAnalysis where
parseJSON = withObject "RSI Quote" $
\o -> do
rsiQuote <- o .: "Technical Analysis: RSI"
date <- rsiQuote .: "2018-10-16"
rsi <- date .: "RSI"
return TechinicalAnalysis {..}
main :: IO ()
main = do
putStrLn "Which ticker? "
symbolToQuote <- getLine
d <- (eitherDecode <$> simpleHttp ("https://www.alphavantage.co/query?function=RSI&interval=weekly&time_period=10&series_type=open&apikey==FI2KMCSDSAE&symbol=" ++ symbolToQuote)) :: IO (Either String TechinicalAnalysis)
case d of
Left e -> print e
Right qt -> print (rsi qt)
我的目标是从链接的JSON文件中获取最新的“ RSI”报价。
我现在不确定该怎么做,因此出于测试目的,我手动对"2018-10-16"
部分中的密钥parseJSON
进行了修改。
我运行代码的错误消息是
• Couldn't match type ‘unordered-containers-0.2.9.0:Data.HashMap.Base.HashMap
Data.Text.Internal.Text Value’
with ‘[Char]’
Expected type: String
Actual type: Object
• In the ‘date’ field of a record
In the first argument of ‘return’, namely ‘TechinicalAnalysis {..}’
In a stmt of a 'do' block: return TechinicalAnalysis {..}
|
27 | return TechinicalAnalysis {..}
| ^^^^^^^^^^^^^^^^^^^^^^^
我认为这是在告诉我,从date
得到的响应date <- rsiQuote .: "2018-10-15"
不是我所期望的。
Here,您可以找到我之前的问题以及后来发现的答案(不同的JSON文件,已成功解析)
答案 0 :(得分:1)
我解决了这个问题。
.:
返回的类型为Object
而不是String
所以代替这个
data TechinicalAnalysis = TechinicalAnalysis {
name :: String,
date :: String,
rsi :: String
} deriving (Show, Generic)
我为此感到愤怒
newtype TechinicalAnalysis = TechinicalAnalysis {
rsi :: String
} deriving (Show, Generic)
,它无缝运行。