将数组解析为结构不同的记录

问题描述

给定以下 JSON:

{
  "data": [
    [1,15,12,16],[2,49,null,43],[3,53,82,31],[4,86,44,null]
  ]
}

我正在尝试将 "data" 的内部内容解析为 Row 的 Haskell 列表,其定义为:

data Row = Row {
    rowElementId :: Int,rowValues    :: [Maybe Int]
}

诀窍是对于每一行,rowElementId 是对应于该行的子数组中的第一个值。从上述 JSON 到记录结构的映射为:

final = [
  Row { rowElementId = 1,rowValues = [Just 15,Just 12,Just 16] },Row { rowElementId = 2,rowValues = [Just 49,Nothing,Just 43] },Row { rowElementId = 3,rowValues = [Just 53,Just 82,Just 31] },Row { rowElementId = 4,rowValues = [Just 86,Just 44,Nothing] }
]  

我设法为 ToJSON 编写了 Row 实例(为了清晰起见,在此公开):

instance ToJSON Row where
    toJSON (Row eid values) =
        toJSONList $ Just eid : values

但是 FromJSON 实例对我来说有点神秘。我认为我在正确的轨道上,但还没有完全到位:

instance FromJSON Row where
    parseJSON (Array arr) = do
        eid <- head arr
        values <- tail arr
        pure $ Row { rowElementId = eid,rowValues = values }

对于上面的代码,编译器抱怨

• Couldn't match type ‘vector-0.12.1.2:Data.Vector.Vector Value’
                 with ‘[aeson-1.5.6.0:Data.Aeson.Types.Internal.Parser EntityId]’
  Expected type: [aeson-1.5.6.0:Data.Aeson.Types.Internal.Parser
                    EntityId]
    Actual type: Array
• In the first argument of ‘head’,namely ‘arr’
  In a stmt of a 'do' block: eid <- head arr

parseJSON (Array arr)中,如何正确地将数组的第一个元素映射到rowElementId,将数组的尾部映射到rowValues,然后返回一个格式良好的{{1} }?

-- 编辑

我可以看到执行 Row 没有意义,因为 head arrarr 而不是 Vector Value。是否有必要显式导入 List 包来实现我想要的,或者是否有另一种方法不需要直接与 Vector 交互?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)