如何用aeson解析数组到元组中? [英] How to parse array into tuple with aeson?
问题描述
如果我有一个数组 [addTask,{id:1,description:d,dependsOn:[],dependentTasks:[]} ]
。
data任务=任务
{id :: String
,description :: String
,dependsOn :: [String]
,dependentTasks :: [String]
}派生(Eq,Show,Generic,ToJSON,FromJSON)
type Change = Storage - >存储
addTask :: Task - >更改
addTask(任务id desc dep dept)=插入id(任务id desc dep dept)
我如何创建一个解析器来生成一个addTask?
instance FromJSON(Storage - > Storage)where
parseJSON(Array v)= do
name< - parseJSON $ v V.! 0 ::只需字符串
任务< - parseJSON $ v V.! 1 ::只要任务
return(addTask任务)
这是我目前的尝试, 't work。
我会继续将数组解析为一个元组 注意:不编译或测试此代码 使用替代方法非常简单,只需定义两个解析器并将它们 我假设 If I have an array How can I create a parser that would produce a addTask from that? This is my current attempt which doesn't work. I would go on and parse the Array into a Tuple Note: I did not compile or test this code Using alternative is really easy you just define two parsers and combine them I am assuming that 这篇关于如何用aeson解析数组到元组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!(String,Task )
,然后使用简单的模式匹配,如果您使用的是 OverloadedStrings
,则可能需要指定addTask的类型,这可以通过 ScopedTypeVariables
(只需将它添加到 .. ::(String,Task)< - parse .. $ c的左侧
$ b $ instance FromJSON(存储 - >存储)其中
parseJSON v = do(addTask ,t)< - parseJSON v
return $ addTask t
编辑
instance FromJSON(存储 - >存储)其中
parseJSON v = let addP = do(addTask,t)< - parseJSON v
return $ addTask t
rmP = do(rmTask,n)< - parseJSON v
在addP中返回$ rmTask n
< |> rmP
rmTask :: Int - >更改
,否则cou始终可以在元组的第一个元素上 case
。["addTask", {"id": "1", "description": "d", "dependsOn": [], "dependentTasks": []}]
. data Task = Task
{ id :: String
, description :: String
, dependsOn :: [String]
, dependentTasks :: [String]
} deriving (Eq, Show, Generic, ToJSON, FromJSON)
type Change = Storage -> Storage
addTask :: Task -> Change
addTask (Task id desc dep dept) = insert id (Task id desc dep dept)
instance FromJSON (Storage -> Storage) where
parseJSON (Array v) = do
name <- parseJSON $ v V.! 0 :: Just String
task <- parseJSON $ v V.! 1 :: Just Task
return (addTask task)
(String,Task)
and then use simple pattern matching, you might need to specify the type of "addTask" if you are using OverloadedStrings
, which can be done with ScopedTypeVariables
(just add it to the left hand side of the .. :: (String, Task) <- parse..
).instance FromJSON (Storage -> Storage) where
parseJSON v = do ("addTask",t) <- parseJSON v
return $ addTask t
Edit
instance FromJSON (Storage -> Storage) where
parseJSON v = let addP = do ("addTask",t) <- parseJSON v
return $ addTask t
rmP = do ("rmTask",n) <- parseJSON v
return $ rmTask n
in addP <|> rmP
rmTask :: Int -> Change
otherwise cou can always case
on the first element of the tuple.