Effect CommunityEC
Effect Community2y ago
4 replies
timolins

Key Order Issue with `S.Struct` in JSON Parsing Using `@effect/schema`

Hello! I'm having troubles with S.Struct messing up the key order of my data:

import { Schema, Schema as S } from "@effect/schema"
import { Effect } from "effect"

const jsonString = JSON.stringify({
  struct: {
    a: "1",
    b: "2",
    c: "3",
    d: true
  },
  record: {
    a: "1",
    b: "2",
    c: "3",
    d: true
  }
})

const StructSchema = S.Struct({
  a: S.String,
  c: S.String,
  b: S.String,
  d: S.Boolean
})

const RecordSchema = S.Record(S.String, S.Union(S.String, S.Boolean))

const configSchema = S.Struct({
  "struct": StructSchema,
  "record": RecordSchema
})

Effect.gen(function*() {
  const output = yield* Schema.decode(S.parseJson(configSchema))(jsonString)
  const doesMatch = JSON.stringify(output) === jsonString

  console.log(output)
  console.log({ doesMatch })
}).pipe(Effect.runPromise)

/*
Output:
{
  struct: { d: true, a: '1', c: '3', b: '2' },
  record: { a: '1', b: '2', c: '3', d: true }
}
*/



In this example, the output data for the S.Record schema is correct, but the struct schema is wrong:
{
  d: true, // This should be at the bottom
  a: "1",
  b: "2",
  c: "3"
}


This is a problem because I'm reading and writing JSON files to disk, and by not respecting the order it creates unwanted diffs in the file.
Was this page helpful?