Giter Site home page Giter Site logo

aeson-deriving's Introduction

aeson-deriving

Build Status Hackage

Define JSON encoding and decoding behavior in a unified way with DerivingVia. This ensures the instances for the two aeson type classes stay in sync and eliminates much needless boilerplate, besides supporting many extra features.

Uses and examples

Basic encoding options & common patterns

Aeson's generics support governs the basic mapping between Haskell definitions and the JSON format. This functionality, along with its tunable parameters, can be specified with the GenericEncoded newtype.

type MyEncoding = GenericEncoded
  '[ ConstructorTagModifier := SnakeCase  -- extensible function support
  , FieldLabelModifier :=
      [ SnakeCase, DropSuffix "_" ]       -- functions can be composed
  , SumEncoding := TaggedObject "type" "contents"
  ]


data User = User
  { firstName :: Text
  , id_       :: UserId
  , companyId :: CompanyId
  }
  deriving stock (Generic, Show)
  deriving (FromJSON, ToJSON)
    via MyEncoding User

data Document = Document
  { name      :: Text
  , id_       :: Int64
  , companyId :: CompanyId
  , parts     :: [SubDocument]
  }
  deriving stock (Generic, Show)
  deriving (FromJSON, ToJSON)
    via MyEncoding Document

-- >>> encode (User "jake" 1 29)
-- { "type": "user", "first_name": "jake", "id": 1, "company_id": 29}

Modifier newtypes

Constrant Fields

data Transaction = Transaction
  { transactionId :: UUID }
  deriving stock (Generic, Show)
  deriving (FromJSON, ToJSON) via
    WithConstantFieldsOut
     '[ "version" := "1.0"
      , "system_info" := "๐Ÿ‘"
      ]
      (MyEncoding Transaction)

Note: Some newtypes that modify the instances come in an inbound and outbound variant. For example WithConstantFields is defined as the composition of WithConstantFieldsIn and WithConstantFieldsOut.

Constant Objects

Sometimes you may need an entire object of constant fields, with no information passing to the haskell representation. This is modeled as a single-value type and can also be used with the WithConstantFields newtype, as long as the base type is wrapped in the EmptyObject newtype (because otherwise unit types do not serialize to the empty object by default).

data Requirements = Requirements
  deriving (Show, Eq, Generic)
  deriving (FromJSON, ToJSON) via
    WithConstantFields
     '[ "api_version" := "2.0"
      , "check_performed" := 'True
      ]
      (EmptyObject Requirements)

Apply arbitrary functions before encoding/decoding

Example: Special treatment for magic values
data Feedback = Feedback
  { comment :: Text }
  deriving stock (Generic, Show)
  deriving (FromJSON, ToJSON) via
    ModifyFieldIn "comment"
      ("booo!" ==> "boo-urns!")
      (MyEncoding Feedback)


-- x ==> y  maps the value x to y and leaves others unchanged
-- Implement your own instances of `KnownJSONFunction` for other behavior

Preventing infinite loops

Newtypes that modify an inner type class instance must be careful not to do so in an infinitely recursive way. Here the inner type should use the generic-based instance, rather than reference the instance being defined.

This package employs a custom compiler error to prevent this very easy mistake.

Improved error messages for sums of records

See RecordSumEncoded documentation.

To be expanded...

aeson-deriving's People

Contributors

fieldstrength avatar tathougies avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.