在 Aeson 中解析嵌套数组

Parsing nested arrays in Aeson

我正在努力使用 Aeson 库解析以下 JSON。
我只对获取 file1 感兴趣,但我似乎无法管理它。
有人有什么建议吗?

JSON

{"files":[["file1.wav",["file2.jpg","file3.jpg"]]]}

我的代码

data File = File Text deriving (Show, Generic, ToJSON)

instance FromJSON File where
  parseJSON jsn = do
    arrays <- parseJSON jsn
    let x = arrays !! 0 !! 0
    return $ File x

错误信息

"Error in $.files[0][1]: parsing Text failed, expected String, but encountered Array"

问题是使用 parseJSONjsn 解析为 homogeneous 列表。但是 "file1.wav" 是一个字符串而 ["file2.jpg", "file3.jpg"] 不是一个字符串。

一个简单的解决方案是直接在json上进行模式匹配,这是一个Value,它可以包含一个异构的Array(尽管它的名字,它实际上是一个同义词来自 vector 库的 Vector

{-# LANGUAGE OverloadedStrings #-}
import Data.Aeson
import qualified Data.Vector as V
import Data.Text (Text)

newtype File = File Text deriving Show

instance FromJSON File where
  parseJSON json = do
    Array arr <- pure json
    Just (Array arr0) <- pure (arr V.!? 0)
    Just (String txt) <- pure (arr0 V.!? 0)
    pure (File txt)

main :: IO ()
main = print (decode' "[[\"file1\", [\"file2\", \"file3\"]]]" :: Maybe File)

((!?) is a safe indexing operator.)