[Haskell-beginners] converting a json encoded radix tree to a haskell data type

Adam Flott adam at adamflott.com
Thu Aug 27 15:04:38 UTC 2015


I'm having trouble converting a JSON encoded Radix tree into a Haskell
data type[1]. I've tried numerous ways to get the FromJSON instances to
handle all cases, but failing miserably.

[1] unfortunately these type layouts are unchangeable as they are auto
generated types from Thrift


Here is a stripped down version of what I'm working with. For the JSON
file, all keys are unknown at parse time. I only know that a key will be
a string and it's value will be another JSON object or a JSON array of
fixed length.

Any help is appreciated.


-- radix.hs --
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}

import Control.Monad (mzero)
import Data.Int
import Data.Typeable

import Data.Aeson
import qualified Data.ByteString.Lazy as BL
import Data.Text.Lazy as TL
import qualified Data.Vector as V

data Things = MkThings {
  thing   :: TL.Text,
  times :: ThingTimes
  } deriving (Show, Eq, Typeable)

data ThingTimes = MkThingtimes {
  ml :: V.Vector Times
  } deriving (Show, Eq, Typeable)

data Times = MkTimes {
  t1 :: Maybe Int32,
  t2 :: Maybe Int32
  } deriving (Show, Eq, Typeable)

instance FromJSON (V.Vector Things) where
  parseJSON _ = return V.empty

decodeRadix ::BL.ByteString -> Either String (V.Vector Things)
decodeRadix = eitherDecode

main :: IO ()
main = do
  j <- BL.readFile "radix.json"
  case decodeRadix j of
    Left err -> error err
    Right r -> print r
-- radix.hs --

-- radix.json --
{
    "a" : {
        "b" : [ 1, 2 ],
        "c" : {
            "d" : [ 3, null ]
        }
    },
    "a2" : { "b2" : [ 4, 5 ] }
}
-- radix.json --



More information about the Beginners mailing list