Haskell Aeson json encoding bytestrings - json

I need to serialize a record in Haskell, and am trying to do it with Aeson. The problem is that some of the fields are ByteStrings, and I can't work out from the examples how to encode them. My idea is to first convert them to text via base64. Here is what I have so far (I put 'undefined' where I didn't know what to do):
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.Aeson as J
import qualified Data.ByteString as B
import qualified Data.ByteString.Base64 as B64
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import qualified GHC.Generics as G
data Data = Data
{ number :: Int
, bytestring :: B.ByteString
} deriving (G.Generic, Show)
instance J.ToJSON Data where
toEncoding = J.genericToEncoding J.defaultOptions
instance J.FromJSON Data
instance J.FromJSON B.ByteString where
parseJSON = undefined
instance J.ToJSON B.ByteString where
toJSON = undefined
byteStringToText :: B.ByteString -> T.Text
byteStringToText = E.decodeUtf8 . B64.encode
textToByteString :: T.Text -> B.ByteString
textToByteString txt =
case B64.decode . E.encodeUtf8 $ txt of
Left err -> error err
Right bs -> bs
encodeDecode :: Data -> Maybe Data
encodeDecode = J.decode . J.encode
main :: IO ()
main = print $ encodeDecode $ Data 1 "A bytestring"
It would be good if it was not necessary to manually define new instances of ToJSON and FromJSON for every record, because I have quite a few different records with bytestrings in them.

parseJson needs to return a value of type Parser B.ByteString, so you just need to call pure on the return value of B64.decode.
import Control.Monad
-- Generalized to any MonadPlus instance, not just Either String
textToByteString :: MonadPlus m => T.Text -> m B.ByteString
textToByteString = case B64.decode (E.encodeUtf8 x) of
Left _ -> mzero
Right bs -> pure bs
instance J.FromJSON B.ByteString where
parseJSON (J.String x) = textToByteString x
parseJSON _ = mzero
Here, I've chosen to return mzero both if you try to decode anything other than a JSON string and if there is a problem with the base-64 decoding.
Likewise, toJSON needs just needs to encode the Text value you create from the base64-encoded ByteString.
instance J.ToJSON B.ByteString where
toJSON = J.toJSON . byteStringToText
You might want to consider using a newtype wrapper instead of defining the ToJSON and FromJSON instances on B.ByteString directly.

Related

How to extract a single value from a JSON object with a single "key-value"?

An Http server returns data in this JSON format:
{
some_value: "fdsafsafdsafs"
}
Object with single key and value.
I want to parse a returned data in that format and I've not been able to. I don't want to create a special data for that.
Instead I want to parse or deconstract/pattern match it and get the value of "some_value"
Code:
import qualified Data.ByteString as BS
import qualified Data.Text as T
import qualified Data.Aeson as Aeson
func1 :: IO (Either MyError BS.ByteString)
func1 = do
resp <- sendRequestAndReturnJsonBody
-- [.........]
I've tried:
1)
case Aeson.decode resp of
Just (Aeson.Object obj) -> -- how to exctract "some_value" from "obj" now?
_ -> _
2)
let (Aeson.Object ("some_value", String s)) = resp
-- [......]
3)
case resp of
(Object obj) ->
case (lookup "some_value" obj) of
Just (String s) -> pure $ Right s
_ -> undefined
All the attemps are wrong.
How do I do it?
Likely in your third attempt, you did not use the lookup of the Data.HashMap.Strict module from the unordered-containers package. You furthermore should enable the OverloadedStrings option to make use of string literals that have a Text type. You thus can implement this as:
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.HashMap.Strict as HM
import qualified Data.ByteString as BS
import qualified Data.Text as T
import qualified Data.Aeson as Aeson
func1 :: IO (Either MyError BS.ByteString)
func1 = do
resp <- sendRequestAndReturnJsonBody
case Aeson.decode resp of
Just (Aeson.Object obj) -> case (HM.lookup "some_value" obj) of
Just (Aeson.String s) -> pure (Right s)
_ -> undefined
_ -> undefined
If we construct a function:
f :: Applicative f => ByteString -> f (Either a Text)
f resp = case Aeson.decode resp of
Just (Aeson.Object obj) -> case (HM.lookup "some_value" obj) of
Just (Aeson.String s) -> pure (Right s)
_ -> undefined
_ -> undefined
It has a type that given resp is a ByteString, it will return an Applicative f => f (Either a Text), hence if in your case resp is indeed a Value, it can return an IO (Either MyError).
For objects that contain one element, we can use the OverloadedLists extension, and thus make use of that to pattern match on a list pattern for that HashMap:
{-# LANGUAGE OverloadedLists, OverloadedStrings #-}
import qualified Data.ByteString as BS
import qualified Data.Text as T
import qualified Data.Aeson as Aeson
func1 :: IO (Either MyError BS.ByteString)
func1 = do
resp <- sendRequestAndReturnJsonBody
case Aeson.decode resp of
Just (Aeson.Object [("some_value", Aeson.String s)]) -> pure (Right s)
_ -> undefined
For more items, this will not match. Trying this for more items can fail, since the order of the items with toList is unspecified, and thus can depend on implementation details.
Even though you said you didn't want to create a custom data type, this is still the most straightforward way of getting the let some_pattern = result syntax that you want. Note that you don't need to use the data type for anything other than parsing. Think of it as the "usual" Aeson method for creating a new pattern that you can match the result on.
You can either use generics to define the data type or write a custom FromJSON instance to avoid cluttering your namespace with a some_value field:
{-# LANGUAGE OverloadedStrings #-}
import Data.ByteString (ByteString)
import Data.Aeson
newtype SomeValue = SomeValue String
instance FromJSON SomeValue where
parseJSON = withObject "SomeValue" $ \o -> SomeValue <$> o .: "some_value"
myjson :: ByteString
myjson = "{ \"some_value\": \"fdsafsafdsafs\" }"
main = do
case decodeStrict myjson of
Just (SomeValue v) -> print v
_ -> error "didn't work!"

how to parse json with field of optional and variant type in Haskell?

How I can parse the input json inside this file ? https://github.com/smogon/pokemon-showdown/blob/master/data/moves.js
For the secondary and flags properties? They are optional and contains variant type.
A minimal example would be this one:
[
{},
{
"secondary": false
},
{
"secondary": {
"chance": 10,
"boosts": {
"spd": -1
}
}
},
{
"secondary": {
"chance": 30,
"volatileStatus": "flinch"
}
},
{
"secondary": {
"chance": 30
}
},
{
"secondary": {
"chance": 10,
"self": {
"boosts": {
"atk": 1,
"def": 1,
"spa": 1,
"spd": 1,
"spe": 1
}
}
}
},
{
"secondary": {
"chance": 10,
"status": "brn"
}
},
{
"secondary": {
"chance": 50,
"self": {
"boosts": {
"def": 2
}
}
}
},
{
"secondary": {
"chance": 100,
"self": {}
}
},
{
"secondary": {
"chance": 50,
"boosts": {
"accuracy": -1
}
}
}
]
For your convenience, you can choose to attach this snippet to the end of the js file and run it using node move.js. Two valid json files will be saved to your disk. One is a list of json objects while the other is an object with string as key.
var fs = require('fs');
fs.writeFile("moves_object.json", JSON.stringify(BattleMovedex), function(err) {}); // 1. save a json object with string key
var jsonList = []
for (var key of Object.keys(BattleMovedex)) {
jsonList.push(BattleMovedex[key]);
}
fs.writeFile("moves.json", JSON.stringify(jsonList), function(err) { // 2. save as a list of json object
if (err) {
console.log(err);
}
});
FYI:
If you are familiar with c++, you might find it easier to understand the same problem in this post:
How to parse json file with std::optional< std::variant > type in C++?
NOTE: In the code examples below, I've used a "moves.json" file whose contents are your minimal example above. Except for getMoves, which can parse any valid JSON, the other code examples won't work on the "moves.json" file derived from the linked "moves.js" file because the format is different (e.g., it's an object, not an array, for one thing).
The simplest way of using Aeson to parse arbitrary JSON is to parse it to a Value:
import Data.Aeson
import Data.Maybe
import qualified Data.ByteString.Lazy as B
getMoves :: IO Value
getMoves = do
mv <- decode <$> B.readFile "moves.json"
case mv of
Nothing -> error "invalid JSON"
Just v -> return v
Any valid JSON can be parsed this way, and the resulting Value has completely dynamic structure that can be programmatically inspected at runtime. The Lens library and Maybe monad can be helpful here. For example, to find the (first) object with a non-missing secondary.chance of 100, you could use:
{-# LANGUAGE OverloadedStrings #-}
import Control.Lens
import Data.Aeson
import Data.Aeson.Lens
import qualified Data.Vector as Vector
import qualified Data.ByteString.Lazy as B
find100 :: Value -> Maybe Value
find100 inp = do
arr <- inp ^? _Array
Vector.find (\s -> s ^? key "secondary" . key "chance" . _Integer == Just 100) arr
test1 = find100 <$> getMoves
which outputs:
> test1
Just (Object (fromList [("secondary",Object (fromList [("chance",Number 100.0),
("self",Object (fromList []))]))]))
which is the Value representation of the object:
{
"secondary": {
"chance": 100,
"self": {}
}
}
If you want the resulting parsed object to have more structure, then you need to start by figuring out a Haskell representation that will work with all possible objects you're planning to parse. For your example, a reasonable representation might be:
type Moves = [Move]
data Move = Move
{ secondary :: Secondary'
} deriving (Show, Generic)
newtype Secondary' = Secondary' (Maybe Secondary) -- Nothing if json is "false"
deriving (Show, Generic)
data Secondary = Secondary
{ chance :: Maybe Int
, boosts :: Maybe Boosts
, volatileStatus :: Maybe String
, self :: Maybe Self
} deriving (Show, Generic)
data Self = Self
{ boosts :: Maybe Boosts
} deriving (Show, Generic)
newtype Boosts = Boosts (HashMap.HashMap Text.Text Int)
deriving (Show, Generic)
This assumes that all moves have a secondary field which is either "false" or an object. It also assumes that lots of boost keys are possible, so it's more convenient to represent them as arbitrary text strings in a Boosts hashmap. Also, this handles having the "boosts" directly under "secondary" or nested within "self", since your example included examples of both forms, though maybe this was a mistake.
For these data types, the default instances for Move, Self, and Secondary can all be used:
instance FromJSON Move
instance FromJSON Self
instance FromJSON Secondary
The Secondary' newtype wrapper around Secondary is then used to handle false versus an object using a custom instance:
instance FromJSON Secondary' where
parseJSON (Bool False) = pure $ Secondary' Nothing
parseJSON o = Secondary' . Just <$> parseJSON o
A custom instance is also needed for Boosts to parse it into the appropriate hashmap:
instance FromJSON Boosts where
parseJSON = withObject "Boosts" $ \o -> Boosts <$> mapM parseJSON o
Now, with the following driver:
test2 :: IO (Either String Moves)
test2 = eitherDecode <$> B.readFile "moves.json"
this decodes your example like so:
> test2
Right [Move {secondary = Secondary' Nothing},Move {secondary =
Secondary' (Just (Secondary {chance = Just 10, boosts = Just (Boosts
(fromList [("spd",-1)])), volatileStatus = Nothing, self =
...
By using eitherDecode above, we can get an error message if the parse fails. For example, if you run this on the "moves.json" derived from "moves.js" instead, you get:
> test2
Left "Error in $: parsing [] failed, expected Array, but encountered Object"
when the parser notices that it's trying to parse a [Move] array but is instead finding an object keyed by Pokemon move names.
Here's the full code showing both types of parsing:
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Lens
import Data.Aeson
import Data.Aeson.Lens
import GHC.Generics
import qualified Data.Text as Text
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Vector as Vector
import qualified Data.ByteString.Lazy as B
--
-- Parse into a dynamic Value representation
getMoves :: IO Value
getMoves = do
mv <- decode <$> B.readFile "moves.json"
case mv of
Nothing -> error "invalid JSON"
Just v -> return v
find100 :: Value -> Maybe Value
find100 inp = do
arr <- inp ^? _Array
Vector.find (\s -> s ^? key "secondary" . key "chance" . _Integer == Just 100) arr
test1 :: IO (Maybe Value)
test1 = find100 <$> getMoves
--
-- Parse into suitable static data structures
-- whole file is array of moves
type Moves = [Move]
data Move = Move
{ secondary :: Secondary'
} deriving (Show, Generic)
newtype Secondary' = Secondary' (Maybe Secondary) -- Nothing if json is "false"
deriving (Show, Generic)
data Secondary = Secondary
{ chance :: Maybe Int
, boosts :: Maybe Boosts
, volatileStatus :: Maybe String
, self :: Maybe Self
} deriving (Show, Generic)
data Self = Self
{ boosts :: Maybe Boosts
} deriving (Show, Generic)
newtype Boosts = Boosts (HashMap.HashMap Text.Text Int)
deriving (Show, Generic)
instance FromJSON Move
instance FromJSON Self
instance FromJSON Secondary
instance FromJSON Secondary' where
parseJSON (Bool False) = pure $ Secondary' Nothing
parseJSON o = Secondary' . Just <$> parseJSON o
instance FromJSON Boosts where
parseJSON = withObject "Boosts" $ \o -> Boosts <$> mapM parseJSON o
test2 :: IO (Either String Moves)
test2 = eitherDecode <$> B.readFile "moves.json"
here is another attempt to your mover.json
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
module Main where
import Control.Applicative
import Data.Maybe
import Data.Text (Text)
import GHC.Generics
import Data.Aeson
main :: IO ()
main = do
result <- eitherDecodeFileStrict "/tmp/helloworld/movers.json"
case ( result :: Either String [Move]) of
Left error -> print error
Right ms -> print (length ms)
data Move = Move
{ num :: Int
, accuracy :: Either Int Bool
, secondary :: Maybe (Either Bool Secondary)
} deriving (Generic, Show)
data Secondary = Secondary
{ chance :: Maybe Int
, volatileStatus :: Maybe Text
, boosts :: Maybe Boosts
, self :: Maybe Self
, status :: Maybe Text
} deriving (Generic, Show)
data Boosts = Boosts
{ atk :: Maybe Int
, def :: Maybe Int
, spa :: Maybe Int
, spd :: Maybe Int
, spe :: Maybe Int
} deriving (Generic, Show)
data Self = Self
{ boosts :: Maybe Boosts
} deriving (Generic, Show)
instance FromJSON Move where
parseJSON (Object v) = Move
<$> v .: "num"
<*> ( (Left <$> v .: "accuracy")
<|> (Right <$> v .: "accuracy")
)
<*> ( fmap (fmap Left) (v .:? "secondary")
<|> fmap (fmap Right) (v .:? "secondary")
)
instance FromJSON Secondary
instance FromJSON Boosts
instance FromJSON Self
My attempt to the minimal sample
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
module Main where
import Data.Text
import GHC.Generics
import Data.Aeson
main :: IO ()
main = do
result <- eitherDecodeFileStrict "/tmp/helloworld/minimal.json"
print (result :: Either String [Foo])
data Foo = Foo { secondary :: Either Bool Bar } deriving (Generic, Show)
data Bar = Chance
{ chance :: Int
, volatileStatus :: Maybe Text
, boosts :: Maybe Boosts
, self :: Maybe Self
, status :: Maybe Text
} deriving (Generic, Show)
data Boosts = Boosts
{ atk :: Maybe Int
, def :: Maybe Int
, spa :: Maybe Int
, spd :: Maybe Int
, spe :: Maybe Int
} deriving (Generic, Show)
data Self = Self
{ boosts :: Maybe Boosts
} deriving (Generic, Show)
instance FromJSON Foo where
parseJSON (Object v) = do
sd <- v .: "secondary" -- Parse Value
case sd of
Bool x -> return . Foo . Left $ x
otherwise -> (Foo . Right) <$> parseJSON sd
instance FromJSON Bar
instance FromJSON Boosts
instance FromJSON Self

Trouble with JSON (Data.Aeson)

I'm new to Haskell and in order to learn the language I am working on a project that involves dealing with JSON. I am currently getting the feeling Haskell is the wrong language for the job, but that isn't the point here.
I've been struggling to understand how this works for a few days. I have searched and everything I have found does not seem to work. Here's the issue:
I have some JSON in the following format:
>>>less "path/to/json"
{
"stringA1_stringA2": {"stringA1":floatA1,
"stringA2":foatA2},
"stringB1_stringB2": {"stringB1":floatB1,
"stringB2":floatB2}
...
}
Here floatX1 and floatX2 are actually strings of the form "0.535613567", "1.221362183" etc. What I want to do is parse this into the following data
data Mydat = Mydat { name :: String, num :: Float} deriving (Show)
where name would correspond to "stringX1_stringX2" and num to floatX1 for X = A,B,...
So far I have reached a 'solution' which feels fairly hackish and convoluted and doesn't work properly.
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
import Data.Functor
import Data.Monoid
import Data.Aeson
import Data.List
import Data.Text
import Data.Map (Map)
import qualified Data.HashMap.Strict as DHM
--import qualified Data.HashMap as DHM
import qualified Data.ByteString.Lazy as LBS
import System.Environment
import GHC.Generics
import Text.Read
data Mydat = Mydat {name :: String, num :: Float} deriving (Show)
test s = do
d <- LBS.readFile s
let v = decode d :: Maybe (DHM.HashMap String Object)
case v of
-- Just v -> print v
Just v -> return $ Prelude.map dataFromList $ DHM.toList $ DHM.map (DHM.lookup "StringA1") v
good = ['1','2','3','4','5','6','7','8','9','0','.']
f x = elem x good
dataFromList :: (String, Maybe Value) -> Mydat
dataFromList (a,b) = Mydat a (read (Prelude.filter f (show b)) :: Float)
Now I can compile this and run
test "path/to/json"
in ghci and it prints a list of Mydat's in the case where "stringX1"="stringA1" for all X. In reality there are two values for "stringX1" so aside from the hackyness this is not satisfactory. There must be a better way to do this. I get that I need to write my own parser probably but I am confused about how this works so any suggestions would be great. Thanks in advance.
The structure of your JSON is pretty nasty, but here's a basic working solution:
#!/usr/bin/env stack
-- stack --resolver lts-11.5 script --package containers --package aeson
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Map as Map
import qualified Data.Aeson as Aeson
data Mydat = Mydat { name :: String
, num :: Float
} deriving (Show)
instance Eq Mydat where
(Mydat _ x1) == (Mydat _ x2) = x1 == x2
instance Ord Mydat where
(Mydat _ x1) `compare` (Mydat _ x2) = x1 `compare` x2
type MydatRaw = Map.Map String (Map.Map String String)
processRaw :: MydatRaw -> [Mydat]
processRaw = Map.foldrWithKey go []
where go key value accum =
accum ++ (Mydat key . read <$> Map.elems value)
main :: IO ()
main =
do let json = "{\"stringA1_stringA2\":{\"stringA1\":\"0.1\",\"stringA2\":\"0.2\"}}"
print $ fmap processRaw (Aeson.eitherDecode json)
Note that read is partial and generally not a good idea. But I'll leave it to you to flesh out a safer version :)
As I commented, the best thing would probably be to make your JSON file well-formed in the sense that the float fields should really be floats, not strings.
If that's not an option, I would recommend you phrase out the type that the JSON file seems to represent as simple as possible (but without dynamic Objects), and then convert that to the type you actually want.
import Data.Map (Map)
import qualified Data.Map as Map
type GarbledJSON = Map String (Map String String)
-- ^ you could also stick with hash maps for everything, but
-- usually `Map` is actually more sensible in Haskell.
data MyDat = MyDat {name :: String, num :: Float} deriving (Show)
test :: FilePath -> IO [MyDat]
test s = do
d <- LBS.readFile s
case decode d :: Maybe GarbledJSON of
Just v -> return [ MyDat iName ( read . filter (`elem`good)
$ iVals Map.! valKey )
| (iName, iVals) <- Map.toList v
, let valKey = takeWhile (/='_') iName ]
Note that this will crash completely if any of the items don't contain the first part of the name as a string of float format, and likely give bogus items when you filter out characters that aren't good. If you just want to ignore any malformed items (which is also not a very clean approach...), you can do it this way:
test :: FilePath -> IO [MyDat]
test s = do
d <- LBS.readFile s
return $ case decode d :: Maybe GarbledJSON of
Just v -> [ MyDat iName iVal
| (iName, iVals) <- Map.toList v
, let valKey = takeWhile (/='_') iName
, Just iValStr <- [iVals Map.!? valKey]
, [(iVal,"")] <- [reads iValStr] ]
Nothing -> []

Haskell Aeson JSON, filter out illegal characters

Using Haskell with the Aeson JSON Hackage, and given the following JSON:
{
"base": "GBP",
"date": "2017-10-27",
"rates": {
"#USD": 1.3093,
"#EUR": 1.1282
}
}
What is the beste way to implement a FromJson instance?
Currently I have this:
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
import GHC.Generics
import Data.Aeson
data Conversion = Conversion {
base :: String,
rates :: Rates }
deriving (Show, Generic)
data Rates = Rates {
eur :: Float,
usd :: Float }
deriving (Show, Generic)
instance FromJSON Conversion
instance FromJSON Rates where
parseJSON (Object o) = trace ( show(o)) Rates <$> o .: "#USD" <*> o .: "#EUR"
I have defined both possibilities in the instance FromJSON Rates. I tried to do it with the more generic way, but the 'illegal' characters # are not allowed in the data part.
So in this case I have only two annoying fields. But if I want to extend this and get multiple annoying characters (#, #, - etc.), do I have to define every field? Or is there a smarter and faster way to achieve the same?
You can deal with this by using fieldLabelModifier and replacing the problematic fields with your own. This allows you to be selective about which names are modified which is very useful if you have large records with only a few weirdly named fields that you can't directly put in your type.
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Data.Aeson
import Data.Aeson.Types
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Map.Strict as M
import GHC.Generics
import System.Environment (getArgs)
data Conversion = Conversion
{ base :: String
, rates :: Rates
} deriving (Show, Generic)
newtype USD = USD Float
newtype EUR = EUR Float
data Rates = Rates
{ eur :: Float
, usd :: Float
}
deriving (Show, Generic)
instance FromJSON Conversion
instance FromJSON Rates where
parseJSON = genericParseJSON opts
where
fields = M.fromList
[("usd", "#USD"), ("eur", "#EUR")]
opts = defaultOptions
{ fieldLabelModifier = \s -> M.findWithDefault s s fields }
main :: IO ()
main = do
[file] <- getArgs
decode <$> BSL.readFile file >>= \case
Nothing -> putStrLn "Parse failed!"
Just conversion -> print (conversion :: Conversion)
With this we get
[nix-shell:/tmp]$ ./T /tmp/rates.json
Conversion {base = "GBP", rates = Rates {eur = 1.1282, usd = 1.3093}}
[nix-shell:/tmp]$ cat /tmp/rates.json
{
"base": "GBP",
"date": "2017-10-27",
"rates": {
"#USD": 1.3093,
"#EUR": 1.1282
}
}
Just remember to use the same Aeson options if you ever define ToJSON instance for your type!

Parsing a nested array of objects with Aeson

I want to parse a JSON object and create a JSONEvent with the given name and args
I'm using Aeson, and right now I'm stucked on converting "args":[{"a": "b"}] to a [(String, String)].
Thank's in advance!
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Data.Aeson
data JSONEvent = JSONEvent [(String, String)] (Maybe String) deriving Show
instance FromJSON JSONEvent where
parseJSON j = do
o <- parseJSON j
name <- o .:? "name"
args <- o .:? "args" .!= []
return $ JSONEvent args name
let decodedEvent = decode "{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"}]}" :: Maybe JSONEvent
Here's a bit more elaborate example based on ehird's example. Note that the explicit typing on calls to parseJSON is unnecessary but I find them useful for documentation and debugging purposes. Also I'm not sure what you intended, but with args with multiple values I simply concatenate all the args together like so:
*Main> decodedEvent2
Just (JSONEvent [("a","b"),("c","d")] (Just "edwald"))
*Main> decodedEvent3
Just (JSONEvent [("a","b"),("c","d")] (Just "edwald"))
Here's the code:
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import qualified Data.Text as T
import qualified Data.Foldable as F
import qualified Data.HashMap.Lazy as HM
import qualified Data.Vector as V
import Data.Aeson
import qualified Data.Attoparsec as P
import Data.Aeson.Types (Parser)
import qualified Data.Aeson.Types as DAT
import qualified Data.String as S
data JSONEvent = JSONEvent [(String, String)] (Maybe String) deriving Show
instance FromJSON JSONEvent where
parseJSON = parseJSONEvent
decodedEvent = decode "{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"}]}" :: Maybe JSONEvent
decodedEvent2 = decode "{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"}, {\"c\": \"d\"}]}" :: Maybe JSONEvent
decodedEvent3 = decode "{\"name\":\"edwald\",\"args\":[{\"a\": \"b\", \"c\": \"d\"}]}" :: Maybe JSONEvent
emptyAesonArray :: Value
emptyAesonArray = Array $ V.fromList []
parseJSONEvent :: Value -> Parser JSONEvent
parseJSONEvent v =
case v of
Object o -> do
name <- o .:? "name"
argsJSON <- o .:? "args" .!= emptyAesonArray
case argsJSON of
Array m -> do
parsedList <- V.toList <$> V.mapM (parseJSON :: Value -> Parser (HM.HashMap T.Text Value)) m
let parsedCatList = concatMap HM.toList parsedList
args <- mapM (\(key, value) -> (,) <$> (return (T.unpack key)) <*> (parseJSON :: Value -> Parser String) value) parsedCatList
return $ JSONEvent args name
_ -> fail ((show argsJSON) ++ " is not an Array.")
_ -> fail ((show v) ++ " is not an Object.")
-- Useful for debugging aeson parsers
decodeWith :: (Value -> Parser b) -> String -> Either String b
decodeWith p s = do
value <- P.eitherResult $ (P.parse json . S.fromString) s
DAT.parseEither p value
I'm not an aeson expert, but if you have Object o, then o is simply a HashMap Text Value; you could use Data.HashMap.Lazy.toList to convert it into [(Text, Value)], and Data.Text.unpack to convert the Texts into Strings.
So, presumably you could write:
import Control.Arrow
import Control.Applicative
import qualified Data.Text as T
import qualified Data.Foldable as F
import qualified Data.HashMap.Lazy as HM
import Data.Aeson
instance FromJSON JSONEvent where
parseJSON j = do
o <- parseJSON j
name <- o .:? "name"
Object m <- o .:? "args" .!= []
args <- map (first T.unpack) . HM.toList <$> F.mapM parseJSON m
return $ JSONEvent args name