Repository navigation
json: encode in declaration order; add indent, escapeHTML, sortKeys - #255
Merged
Merged
Conversation
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]>
Deploying dang with
|
| 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 |
vito
force-pushed
the
json-encode-options
branch
from
November 7, 2026 03:06
1ae4b65 to
1c0d859
Compare
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
force-pushed
the
json-encode-options
branch
from
November 8, 2026 15:59
1c0d859 to
2f6028b
Compare
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
force-pushed
the
json-encode-options
branch
from
November 8, 2026 23:45
2f6028b to
a99bf6f
Compare
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
JSON.encodewas Go'sjson.Marshaland nothing else: compact output,</>/&escaped, object and record keys sorted alphabetically. To write a committedmodules.jsonthe way Go'sjson.Encoderdoes (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 ajstrthat undoes\u003c/\u003e/\u0026.This makes
JSON.encodewrite keys in declaration order by default, like Go'sjson.Marshaldoes for structs, and adds three optional arguments:sortKeys: false): atype'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 changesJSON.encode's default output; see Release notes below.sortKeys: truesorts 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.indentpretty-prints, matchingjson.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.Encodeadds one;Marshaldoesn't).escapeHTML: falsewrites<>&as-is, likeEncoder.SetEscapeHTML(false).Together with the existing
@JSON.field(name:, omitNull:, omitEmpty:), a modules.json-style encoder becomes a typedtypeplus one call:Record order relies on #261 (now in main), which makes record literals list their fields as written.
Release notes
Implementation notes
valueEncoderbuilds every object as an orderedjson.RawMessage. Fields are ranked byobj.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: truedecodes 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.unescapeJSONHTML, thenjson.Indent). I didn't useMarshalIndentor anEncoderbecause parts of the tree are already-marshaledjson.RawMessagethat 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 textu003cstays intact (tested).json.Indentis exactly whatMarshalIndentruns afterMarshal.type A { pub one = [1]; two: Int! = 2 }listedtwofirst.ObjectDecl.Infernow orders the type's bindings as declared, using records: keep {{ }} fields in the order written #261'sorderBindings. This affects anything that iterates a type's bindings; the full test suite (tests,pkg/dang,pkg/lsp,cmd/dang, docs) passes.case u: Userstill matches it (tested).Decisions
toString/List.joinnow use the same ordered encoder (toStringJSON) instead ofObject.MarshalJSON, sotoString(x)andJSON.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.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.sortKeysstays.Tests and docs
tests/test_json_encode_options.dang: default layout, indent with spaces and tabs, empty[]/{}, layout combined withsortKeys: 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/joinagreeing withJSON.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 matchescase u: User.test_json.dangandtest_codec_field_directives.dang.tests/test_scalar_non_string.dang: raw-JSON scalar leaves get indented.docs/lit/data/json-yaml.md, and the record notes indocs/lit/language/syntax.md(including its example) and the syntax skill.