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

℡╲_俬逩灬. 提交于 2020-03-03 17:15:41

问题


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?

来源:https://stackoverflow.com/questions/59122804/in-aeson-schemas-how-do-you-construct-an-object-of-a-schematype-without-encoding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!