Reputation: 11321
I'm a haskell beginner. In Python, I can do this:
>>> import json
>>> data = {'name': 'Jono', 'age': 36, 'skill': 'beginner'}
>>> json.dumps(data)
'{"name": "Jono", "age": 36, "skill": "beginner"}'
So I'm trying to do the same thing in Haskell. Here's what I've tried:
*Main Data.Aeson> myData = [("name", "Jono"), ("age", "36"), ("skill", "beginner")]
*Main Data.Aeson> toJSON myData
Array [Array [String "name",String "Jono"],Array [String "age",String "36"],Array [String "skill",String "beginner"]]
*Main Data.Aeson> encode $ toJSON myData
"[[\"name\",\"Jono\"],[\"age\",\"36\"],[\"skill\",\"beginner\"]]"
I can't quite get it to output JSON. How can I do that? I've looked at the Data.Aeson documentation on Hackage, but I can't make heads or tails of it.
Upvotes: 4
Views: 806
Reputation: 152867
Python frequently uses hashmaps as a lightweight data structure. In Haskell, data types are lightweight enough that it is idiomatic to just make one whenever you need to instead.
{-# LANGUAGE TemplateHaskell #-}
import Data.Aeson
import Data.Aeson.TH
data Person = Person
{ name :: String
, age :: Int
, skill :: String -- you should probably use a more structured type here
}
deriveJSON defaultOptions ''Person
Then you can use it. No need to call toJSON
first.
> encode Person { name = "Jono", age = 36, skill = "beginner" }
"{\"name\":\"Jono\",\"age\":36,\"skill\":\"beginner\"}"
(Don't be fooled by the extra escaping and quote marks: this is just how the repl displays string-y things to avoid ambiguity. The ByteString
being displayed is indeed a valid JSON object.)
This is almost identical to the example given at the beginning of the documentation; I encourage you to read that page, as there's lots of good information there.
Upvotes: 10
Reputation: 64740
As @felk said, use a map:
Prelude> import Data.Aeson
Prelude Data.Aeson> import Data.Map
Prelude Data.Aeson Data.Map> myData = fromList [("name", "Jono"), ("age", "36"), ("skill", "beginner")]
Prelude Data.Aeson Data.Map> encode $ toJSON myData
"{\"age\":\"36\",\"name\":\"Jono\",\"skill\":\"beginner\"}"
...> Data.ByteString.Lazy.Char8.putStrLn $ encode $ toJSON myData
{"age":"36","name":"Jono","skill":"beginner"}
Upvotes: 9