Haskell-type modeling method with dynamic JSON fields?

I am new to Haskell based on imperative programming. I would like to be able to serialize the object in JSON in the "Haskell way", but not quite sure how to do this.

I read Chapter 5 of RealWorldHaskell , which talks a bit about JSON, and it played with Aeson. I also looked at several JSON API libraries written in Haskell, for example:

This allowed me to create very simple JSON strings from objects (also thanks to this blog post ):

{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}

import Data.Aeson
import GHC.Generics

data User = User {
  email :: String,
  name :: String
} deriving (Show, Generic)

instance ToJSON User

main = do
  let user = User "foo@example.com" "Hello World"
  let json = encode user
  putStrLn $ show json

This will print:

"{\"email\":\"foo@example.com",\"name\":\"Hello World\"}"

User, . API- Facebook Graph data, JSON . , Facebook API (, API Facebook):

POST api.facebook.com/actions
{
  "name": "read",
  "object": "book",
  "data": {
    "favoriteChapter": 10,
    "hardcover": true
  }
}

name object - String, data - .

, " Haskell", User ?

, :

data User = User {
  email :: String,
  name :: String,
  data :: CustomData
} deriving (Show, Generic)

data CustomData = CustomData {
  favoriteColor :: String
}

, . , User JSON :

{
  "email": "",
  "name": "",
  "data": {
    "favoriteColor": ""
  }
}

, , , User , , data, ( - , ).

+4
2

, . , , , " " .

. , , . : http://bitemyapp.com/posts/2014-04-17-parsing-nondeterministic-data-with-aeson-and-sum-types.html

:

data CustomData = NotesData Text | UserAge Int deriving (Show, Generic)
newtype Email = Email Text deriving (Show, Generic)
newtype Name  = Name  Text deriving (Show, Generic)

data User = User {
  email :: Email,
  name  :: Name,
  data  :: CustomData
} deriving (Show, Generic)

, . : http://bitemyapp.com/posts/2014-04-11-aeson-and-user-created-types.html

newtype Email = Email Text deriving (Show, Generic)
newtype Name  = Name  Text deriving (Show, Generic)

-- 'a' needs to implement ToJSON/FromJSON as appropriate
data User a = User {
  email :: Email,
  name  :: Name,
  data  :: a
} deriving (Show, Generic)

data User . User . data , , User CustomData, User Text User Int. , , Int/String. newtype, .

, , (Double, Double), . https://github.com/NICTA/coordinate.

, . , , , .

JSON , https://github.com/bitemyapp/bloodhound

, , . " ", .

: https://www.haskell.org/haskellwiki/Smart_constructors

+4

JSON Aeson FromJSON, user:: Value, Aeson JSON. JSON , FromJSON, , .

+2

All Articles