user1002430
user1002430

Reputation:

How to use Haskell "json" package to parse to type [Map String String]?

I've got some sample JSON data like this:

[{
  "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):

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?

Upvotes: 2

Views: 192

Answers (1)

zakyggaps
zakyggaps

Reputation: 3080

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

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.

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.

Upvotes: 1

Related Questions