Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I encode data to JSON using Haskell?

Tags:

haskell

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.

like image 423
Jonathan Avatar asked Sep 02 '25 09:09

Jonathan


1 Answers

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.

like image 98
Daniel Wagner Avatar answered Sep 05 '25 01:09

Daniel Wagner