Loading JSON to Haskell Converter...
Please wait a moment

How to Convert JSON to Haskell Data Types - Step by Step Guide

Step 1

Paste or upload your JSON

Start with the JSON your API sends back, or press Sample. This is what the Sample button loads:

{
  "userId": 12345,
  "username": "haskeller",
  "email": "[email protected]",
  "isActive": true,
  "preferences": [
    "pure_functions",
    "lazy_evaluation",
    "type_safety"
  ],
  "profile": {
    "firstName": "Haskell",
    "lastName": "Curry",
    "age": 35,
    "country": "UK"
  }
}
Step 2

Choose a type name and whether you want aeson

Two settings sit above the editors. Type Name decides what the top-level record is called. Use Aeson adds aeson instances so the records can be decoded from JSON and encoded back; untick it when you only want the types.

•
Records: each object becomes a data type with record syntax, deriving Show and Eq
•
Nested objects: each one gets its own record, named after its key
•
Lists: become Haskell lists, and a list of objects gets one record merged from every item
Step 3

Read the generated records

For the Step 1 JSON the page writes the records below, after a short comment and the imports. The profile object became its own Profile record (it gets the same two instances as Root), and the preferences array became [Text].

data Root = Root
  { rootUserId :: Int
  , rootUsername :: Text
  , rootEmail :: Text
  , rootIsActive :: Bool
  , rootPreferences :: [Text]
  , rootProfile :: Profile
  } deriving (Show, Eq)

instance FromJSON Root where
  parseJSON = withObject "Root" $ \o ->
    Root
      <$> o .: "userId"
      <*> o .: "username"
      <*> o .: "email"
      <*> o .: "isActive"
      <*> o .: "preferences"
      <*> o .: "profile"

instance ToJSON Root where
  toJSON v =
    object
      [ "userId" .= rootUserId v
      , "username" .= rootUsername v
      , "email" .= rootEmail v
      , "isActive" .= rootIsActive v
      , "preferences" .= rootPreferences v
      , "profile" .= rootProfile v
      ]

data Profile = Profile
  { profileFirstName :: Text
  , profileLastName :: Text
  , profileAge :: Int
  , profileCountry :: Text
  } deriving (Show, Eq)
Step 4

Copy or download GeneratedTypes.hs

Save the download as GeneratedTypes.hs next to your code, list aeson and text in your Cabal or Stack dependencies, and decode the JSON like this:

import qualified Data.ByteString.Lazy as BL
import Data.Aeson (eitherDecode)
import qualified Data.Text as T
import GeneratedTypes

main :: IO ()
main = do
  result <- eitherDecode <$> BL.readFile "user.json"
  case result of
    Left err -> putStrLn ("Could not read user.json: " ++ err)
    Right user -> putStrLn (T.unpack (rootUsername user) ++ " lives in " ++ T.unpack (profileCountry (rootProfile user)))

What is JSON to Haskell Conversion?

Haskell code works best with typed data, but writing a record and two aeson instances for every object in a big API response gets tedious fast, and it is easy to forget that some items leave a field out. This page reads your JSON and writes those records for you, with field types that fit every value it saw.

The output is a plain Haskell module. If your data is XML rather than JSON, the XML to Haskell converter writes records with parse functions for xml-conduit.

Frequently Asked Questions

Which packages does the generated module need?

aeson for the FromJSON and ToJSON instances and text for Text fields. If some decimals sit next to integers too long for a Double, the field is typed Scientific, and then the scientific package is needed too. The comment at the top of the output lists exactly what that file uses. The code compiles cleanly with ghc -Wall.

Why are the instances written out instead of derived with Generic?

Generic deriving takes the JSON key from the Haskell field name, so a key like first-name, 2nd or type could never match. Here each record gets a small withObject parser and an object writer that name the original key, while the Haskell fields get safe names. Fields that can be missing are read with .:? so a missing key or a null both give Nothing.

How are numbers typed?

From how each number is written in your JSON, not from a rounded copy. Whole numbers that fit 32 bits become Int, bigger ones become Int64 (so 8901240544102066246 keeps every digit), and anything past 64 bits becomes Integer. Numbers with a decimal point or exponent, such as 14.50 or 1e3, become Double. A quoted value like "00501" stays Text.

What happens with lists whose items differ?

Every item is looked at, not only the first one. A field that is missing or null in some items becomes Maybe, a field that holds both whole and decimal numbers becomes Double, and a field whose values have different kinds, like a number in one item and text in another, becomes aeson Value so nothing is lost.

Can I convert a JSON array instead of an object?

Yes. A list of objects turns into one record built from all the items, and the comment at the top tells you to decode it as [Root]. A single number, a string or a list of plain values has nothing to build a record from, so the page says so instead of writing code.

Is my JSON sent anywhere?

No. The Haskell code is generated in your browser and the JSON is not uploaded to a server. Nothing is kept either: reloading the page starts with an empty editor.