I have the following Haskell code which encodes a list of the data type User
in JSON and prints it to the standard output:
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson
import Data.Text
import qualified Data.ByteString.Lazy.Char8 as B
data User = User
{ id :: String
, name :: String
, address :: String
} deriving (Show)
instance ToJSON User where
toJSON (User id name address) = object
[ pack id .= object
[ "name" .= name
, "address" .= address
]
]
users :: [User]
users = [ User "user 1" "name of user 1" "address of user 1"
, User "user 2" "name of user 2" "address of user 2"
]
main :: IO ()
main = B.putStrLn $ encode users
At the moment, the code produces the following output:
[
{
"user 1": {
"address": "address of user 1",
"name": "name of user 1"
}
},
{
"user 2": {
"address": "address of user 2",
"name": "name of user 2"
}
}
]
However, I would like to output the following JSON structure (joining the inner two objects):
{
"user 1": {
"name": "name of user 1",
"address": "address of user 1"
},
"user 2": {
"name": "name of user 2",
"address": "address of user 2"
}
}
How will I have to change toJSON
in order to print the desired encoded JSON?