Effect CommunityEC
Effect Community3y ago
279 replies
TheStockBroker

Handling JSON Strings in Schema

Continuing the thread @Alex Dixon started. I think that Schema should have some idiomatic way to handle json strings. The following is the natural way to describe this schema, but it's unsafe and doesn't compile (a correct type error)
const fromJson = Schema.string.pipe(
  Schema.transform(
    Schema.unknown, 
    JSON.parse,  // <- unsafe
    JSON.stringify
  ),
  Schema.compose(ExpectedShape) // <- type error
)

But the dream api could be something like
// a jsonString combinator
const fromJson = Schema.jsonString(Foo) // Schema<string,Foo>
Schema.JsonString // Schema<string,unknown>
const wontWork = Schema.compose(Schema.JsonString, Foo)

// a parseJson parser constructor
const fromJson = Schema.parseJson(Foo)
type fromJson = (_: string, opts: ParseOptions) => 
  Effect<never, ParseError, Foo>


The more effect-native you become, the more this problem pops up. I don't think this should be hacked to work as this is native and frequent behavior in node. What do you think?
Was this page helpful?