Skip to content

allNullaryToStringTag has different results if sum has records #1153

@Vonfry

Description

@Vonfry

Here is the example codes:

{-# LANGUAGE DeriveGeneric #-}
module Main where

import Data.Aeson
import GHC.Generics

data Foo = Foo | Bar { bar :: Int } deriving (Generic, Show)

serdeOptions :: Options
serdeOptions = defaultOptions
    { sumEncoding = ObjectWithSingleField
    , allNullaryToStringTag = True
    }

instance ToJSON Foo where
    toJSON = genericToJSON serdeOptions

main = do
    print $ encode $ Foo
    print $ encode $ Bar { bar = 1 }

It prints:

"{\"Foo\":[]}"
"{\"Bar\":{\"bar\":1}}"

As my expect, the first should be "\"Foo\"", which is the default behavior of serde if an enum without arguments.

If Foo is defined as data Foo = Foo | Bar, the output is "\"Foo\"" and "\"Bar\"".
If Foo is defined as data Foo = Foo {} | ... the output is "{\"Foo\":[]}" as well.

Is the current behavior a feature or bug? If it is a feature, is it a good idea to add a new option in sumEncoding to support this?

In my opinion,

  • data Foo = Foo | Bar { ... } should be "\"Foo\""
  • data Foo = Foo () | ... should be {\"Foo\":[]}
  • data Foo = Foo {} | ... should be {\"Foo\":{}}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions