如何使用Haskell“json”包解析以输入[Map字符串]?

时间:2022-03-09 17:04:05

I've got some sample JSON data like this:

我有一些像这样的JSON数据样本:

[{
  "File:FileSize": "104 MB",
  "File:FileModifyDate": "2015:04:11 10:39:00-07:00",
  "File:FileAccessDate": "2016:01:17 22:37:23-08:00",
  "File:FileInodeChangeDate": "2015:04:26 07:50:50-07:00"
}]

and I'm trying to parse the data using the json package (not aeson):

我正在尝试使用json包(不是aeson)解析数据:

import qualified Data.Map.Lazy as M
import Text.JSON

content <- readFile "file.txt"
decode content :: Result [M.Map String String]

This gives me an error:

这给了我一个错误:

Error "readJSON{Map}: unable to parse array value"

I can get as far as this:

我可以做到:

fmap 
  (map (M.fromList . fromJSObject)) 
  (decode content :: Result [JSObject String])

but it seems like an awfully manual way to do it. Surely the JSON data could be parsed directly into a type [Map String String]. Pointers?

但这似乎是一种非常手工的方法。当然,JSON数据可以直接解析为类型[映射字符串]。指针?

1 个解决方案

#1


1  

Without MAP_AS_DICT switch, the JSON (MAP a b) instance will be:

没有MAP_AS_DICT切换,JSON (MAP a b)实例将是:

instance (Ord a, JSON a, JSON b) => JSON (M.Map a b) where
  showJSON = encJSArray M.toList
  readJSON = decJSArray "Map" M.fromList

So only JSON array can be parsed to Data.Map, otherwise it will call mkError and terminate.

因此只有JSON数组可以解析为数据。映射,否则它将调用mkError并终止。

Due to haskell's restriction on instances, you won't be able to write an instance for JSON (Map a b) yourself, so your current workaround may be the best solution.

由于haskell对实例的限制,您无法自己为JSON (Map ab)编写实例,因此当前的解决方案可能是最好的解决方案。

#1


1  

Without MAP_AS_DICT switch, the JSON (MAP a b) instance will be:

没有MAP_AS_DICT切换,JSON (MAP a b)实例将是:

instance (Ord a, JSON a, JSON b) => JSON (M.Map a b) where
  showJSON = encJSArray M.toList
  readJSON = decJSArray "Map" M.fromList

So only JSON array can be parsed to Data.Map, otherwise it will call mkError and terminate.

因此只有JSON数组可以解析为数据。映射,否则它将调用mkError并终止。

Due to haskell's restriction on instances, you won't be able to write an instance for JSON (Map a b) yourself, so your current workaround may be the best solution.

由于haskell对实例的限制,您无法自己为JSON (Map ab)编写实例,因此当前的解决方案可能是最好的解决方案。