yantrakaar
yantrakaar

Reputation: 364

Custom record to json key conversion in Haskell using Aeson library

Below code does not work for me. Can anyone explain how to solve and avoid below kind of errors in Haskell

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}

module Test where

import GHC.Generics
import Data.Aeson.Types
import Data.Aeson

data Person = Person { personId :: Int , personName :: String} deriving (Show, Generic)

instance ToJSON Person where
    toJson p = [
            "id" .= personId p,
            "name" .= personName p
        ]

instance FromJSON Person

I am getting following error. I am not able to figure out the issue here.

Prelude> :load src/User/Test
[1 of 1] Compiling Test             ( src\User\Test.hs, interpreted )

src\User\Test.hs:13:5: error:
    `toJson' is not a (visible) method of class `ToJSON'
Failed, modules loaded: none.

Upvotes: 1

Views: 271

Answers (1)

Jon Purdy
Jon Purdy

Reputation: 54999

The name of the method is toJSON, not toJson. Identifiers are case-sensitive in Haskell. You can find this in the aeson documentation for the ToJSON class.

Upvotes: 1

Related Questions