Search code examples
haskellaeson

In aeson-schemas how do you construct an Object of a SchemaType without encoding to text and decoding back?


I'm using aeson-schemas-1.0.3 and I want to construct values of Object Example without round-tripping through an external serialized representation. It seems like a hack and I'm worried about the performance impact.

I have this schema defined:

type Example = [schema|
  {
    example: Text,
  }
|]

I want to be able to write something like this:

coerceJson $ object [ "example" .= ("Example" :: Text) ]

I have a workaround which does allow that, but it involves encoding to a ByteString and decoding to the Object of the desired SchemaType, which seems expensive and inelegant:

coerceJson :: FromJSON a => Value -> a
coerceJson = fromJust . decode . encode

This seems terribly inefficient.

Here's an SSCCE (Short, Self Contained, Correct (Compilable), Example) with my hack workaround employed. It works, but I'm convinced there's a better solution.

#!/usr/bin/env stack
{- stack
    runghc
    --resolver lts-14.15
    --package aeson-schemas-1.0.3
    --package aeson
    --package text
-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}

import Data.Aeson (decode, encode, object, (.=), FromJSON, Value)
import Data.Aeson.Schema
import Data.Aeson.Text (encodeToLazyText)
import Data.Maybe (fromJust)
import qualified Data.Text.IO as T
import Data.Text(Text)
import Data.Text.Lazy (toStrict)


main :: IO ()
main = do
  let example = coerceJson $ object [ "example" .= ("Example" :: Text) ]
  useExample example


useExample :: Object Example -> IO ()
useExample example = T.putStrLn $ toStrict $ encodeToLazyText $ object [
    "example" .= [get| example.example|]
  ]

coerceJson :: FromJSON a => Value -> a
coerceJson = fromJust . decode . encode


type Example = [schema|
  {
    example: Text,
  }
|]

In aeson-schemas how do you construct an Object of a SchemaType without encoding to text and decoding back?


Solution

  • I'm the author of aeson-schemas. There is currently no way to make a literal Object. The issue with what you're trying to do is, how do you know that the literal Object matches the schema? It's possible I could make an unsafeObject quasiquoter that would assume the object matches the schema you type it as.

    I know this is old, but if you're still having problems with this, what exactly is your use-case? Often times, you'll be loading JSON data from an external source, like an API or a file.