Skip to content

json: encode in declaration order; add indent, escapeHTML, sortKeys - #255

Merged
vito merged 6 commits into
mainfrom
json-encode-options
Nov 8, 2026
Merged

vito merged 6 commits into
mainfrom
json-encode-options

Conversation

@vito

@vito vito commented Nov 7, 2026 •

Copy link
Copy Markdown
Owner

JSON.encode was Go's json.Marshal and nothing else: compact output, </>/& escaped, object and record keys sorted alphabetically. To write a committed modules.json the way Go's json.Encoder does (SetIndent("", " "), SetEscapeHTML(false), keys in struct-field order), dagger/dagger.io#5802 had to hand-write a whole JSON encoder in Dang: jobj/jarr/jm/jmIf, plus a jstr that undoes \u003c/\u003e/\u0026.

This makes JSON.encode write keys in declaration order by default, like Go's json.Marshal does for structs, and adds three optional arguments:

JSON.encode(value, indent: String! = "", escapeHTML: Boolean! = true, sortKeys: Boolean! = false)
  • Default order (sortKeys: false): a type's fields in declaration order, like Go struct fields. Records keep the order they were built in: a literal's fields as written, a selection's as selected (GraphQL inline fragments included), a decoded record's as its type lists them. Maps keep insertion order, as they already did. This changes JSON.encode's default output; see Release notes below.
  • sortKeys: true sorts the keys of every object: records, typed objects, maps (new: maps used to keep insertion order no matter what), and objects inside raw-JSON scalar leaves.
  • indent pretty-prints, matching json.MarshalIndent(v, "", indent). It must contain only spaces and tabs, because anything else would produce output that isn't JSON. There's no trailing newline (Encoder.Encode adds one; Marshal doesn't).
  • escapeHTML: false writes <>& as-is, like Encoder.SetEscapeHTML(false).

Together with the existing @JSON.field(name:, omitNull:, omitEmpty:), a modules.json-style encoder becomes a typed type plus one call:

type Module {
  name: String!
  source: String!
  pin: String @JSON.field(name: "pinned", omitEmpty: true)
  deps: [String!]! @JSON.field(omitEmpty: true) = []
}

JSON.encode({{version: 1, modules: mods}}, indent: "  ", escapeHTML: false)

Record order relies on #261 (now in main), which makes record literals list their fields as written.

Release notes

JSON.encode keeps declaration order. Objects of a type encode their fields in declaration order, records in the order written (or selected), and maps in insertion order, like Go's json.Marshal of a struct. Previously, object and record keys were sorted alphabetically. Pass sortKeys: true for sorted output; it now sorts map keys too. toString and List.join, which JSON-encode non-string values, follow the same order. New options: indent (pretty-printing) and escapeHTML: false. This is a behavior change with no version gate: output that relied on sorted keys (golden files, string comparisons) will change.

Implementation notes

  • Ordering: for JSON, valueEncoder builds every object as an ordered json.RawMessage. Fields are ranked by obj.Mod.Bindings (the type's binding order), and any fields the type doesn't declare go after, sorted by name. Map entries are built in insertion order, through the same helper maps already used. YAML and TOML are unchanged; they sort.
  • sortKeys: true decodes the compact output into Go maps (UseNumber, so number text is preserved) and marshals it again. That's the only way to also sort the keys inside raw-JSON leaves, which the encoder never looks into.
  • Indent and escaping run as passes over the compact output (unescapeJSONHTML, then json.Indent). I didn't use MarshalIndent or an Encoder because parts of the tree are already-marshaled json.RawMessage that were HTML-escaped when they were marshaled, and an Encoder can't undo that. The unescape pass walks escapes two bytes at a time, so an escaped backslash followed by the text u003c stays intact (tested). json.Indent is exactly what MarshalIndent runs after Marshal.
  • A type's binding order is now its declaration order. Previously, fields annotated with a type were bound at hoisting and fields typed by their initializer were bound later, so type A { pub one = [1]; two: Int! = 2 } listed two first. ObjectDecl.Infer now orders the type's bindings as declared, using records: keep {{ }} fields in the order written #261's orderBindings. This affects anything that iterates a type's bindings; the full test suite (tests, pkg/dang, pkg/lsp, cmd/dang, docs) passes.
  • GraphQL inline fragments: an inline-fragment record built from a GraphQL response was typed by the schema's concrete type, so its fields came out in schema order. It's now typed by the fragment's narrowed member, the same way fragments on native values already were. case u: User still matches it (tested).

Decisions

  • toString / List.join now use the same ordered encoder (toStringJSON) instead of Object.MarshalJSON, so toString(x) and JSON.encode(x) agree on order. They still write each field under its own name, without @JSON.field/@JSON.ignore, as before. Object.MarshalJSON, which is used for state retention, is untouched and still sorts keys. String interpolation (${record}) doesn't JSON-encode objects at all, so it's unaffected.
  • Annotated records: let x: {{b: Int!, a: Int!}} = {{a: 1, b: 2}} encodes as {"a":1,"b":2} (the literal's order), while a value decoded into that type encodes as {"b":2,"a":1}. Accepted; documented and tested.
  • No YAML indent option.
  • The name sortKeys stays.

Tests and docs

  • tests/test_json_encode_options.dang: default layout, indent with spaces and tabs, empty []/{}, layout combined with sortKeys: true, escape edge cases, maps with nested objects, field directives, rejecting a bad indent.
  • tests/test_json_encode_key_order.dang: types (including fields typed by their initializer), renamed and omitted fields, records with forward references, selections, decoded vs annotated records, maps of records sorted and unsorted, new() assigning in a different order, toString/join agreeing with JSON.encode, and the full modules.json-style output.
  • tests/test_union_nested_inline_fragments.dang: a GraphQL inline fragment's record comes out in the order selected and still matches case u: User.
  • Updated tests that asserted alphabetical output: test_json.dang and test_codec_field_directives.dang.
  • tests/test_scalar_non_string.dang: raw-JSON scalar leaves get indented.
  • Docs: the stdlib reference skill (Serialization, Maps), docs/lit/data/json-yaml.md, and the record notes in docs/lit/language/syntax.md (including its example) and the syntax skill.

vito added 3 commits November 7, 2026 02:38
JSON.encode is json.Marshal: compact and HTML-escaping. Files meant for
people and diffs (a committed modules.json, say) want what a json.Encoder
with SetIndent and SetEscapeHTML(false) writes, which Dang code could
only get by hand-writing an encoder.

Both options are applied to the compact output as a whole: parts of the
tree are already-marshaled json.RawMessage (ordered maps, scalar leaves),
escaped when they were marshaled, so MarshalIndent or an Encoder could
not unescape them. The defaults leave the output byte-for-byte unchanged.

Signed-off-by: Alex Suraci <[email protected]>
json.Marshal sorts map keys but writes struct fields in declaration
order, and Go-written files people commit follow the latter.
JSON.encode(sortKeys: false) does the same for Dang objects: a type's
fields in the order it declares them, a record's as written (or
selected, or as its type declares them). Maps keep insertion order
either way.

It is an opt-in rather than a new default, which would change existing
output: language versions only gate syntax, so a version could not flip
a builtin's behavior without the interpreter branching on it.
A record's encoded order is the order it was built in, so a literal
annotated with a record type listing its fields differently keeps the
literal's order while a decoded record follows the type. Say so, pin it
in a test, and fix the records docs that still said JSON keys are never
in declaration order. The docs example now declares fields
out of alphabetical order so the two encodings differ.

Signed-off-by: Alex Suraci <[email protected]>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Deploying dang with  Cloudflare Pages  Cloudflare Pages

Latest commit: a99bf6f
Status: ✅  Deploy successful!
Preview URL: https://1f61ccef.dang-3kk.pages.dev
Branch Preview URL: https://json-encode-options.dang-3kk.pages.dev

View logs

vito added 2 commits November 8, 2026 15:49
JSON.encode now writes keys the way Go's json.Marshal writes a struct by
default: a type's fields in declaration order, a record's as written, and a
map's entries in insertion order. sortKeys flips to an opt-in that sorts
every object's keys, maps included, and objects inside raw JSON scalar
leaves too, by round-tripping the output through Go maps.

This changes JSON.encode's default output, which is accepted as a behavior
change with no version gate. toString and List.join follow the same order,
so they agree with JSON.encode, but they still write fields under their own
names: codec directives don't apply to them.

Signed-off-by: Alex Suraci <[email protected]>
A type's members are bound as inference reaches them: annotated fields
when hoisted, fields typed by their initializer later. So
`type A { pub one = [1]; two: Int! = 2 }` listed two before one, and
JSON.encode's declaration order didn't hold for it. Order the type's
bindings as declared once its body is inferred, as record literals do.

A GraphQL inline fragment's record was also typed by the schema's
concrete type, so its fields came out in schema order rather than as
selected. Type it by the fragment's narrowed member, as fragments on
native values already are.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the json-encode-options branch from 1c0d859 to 2f6028b Compare November 8, 2026 15:59
@vito
vito changed the base branch from main to record-literal-order November 8, 2026 16:00
@vito vito changed the title json: add indent, escapeHTML, and sortKeys to JSON.encode json: encode in declaration order; add indent, escapeHTML, sortKeys Nov 8, 2026
@vito
vito changed the base branch from record-literal-order to main November 8, 2026 22:10
JSON.encode's layout and key order must not affect what strict decoding
accepts: pin that indented, sorted output with renamed and omitted fields
decodes back under strict: true.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the json-encode-options branch from 2f6028b to a99bf6f Compare November 8, 2026 23:45
@vito
vito merged commit 84d1741 into main Nov 8, 2026
9 checks passed
vito added a commit that referenced this pull request Nov 9, 2026
JSON.encode now writes fields in declaration order and takes indent,
escapeHTML and sortKeys (#255). A JSON value goes through them like any
other object: a cast keeps its written key order unless sortKeys sorts
it, indent lays out its insides, and escapeHTML applies to its strings.
Tested, and the record test now expects declaration order.

Signed-off-by: Alex Suraci <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant