Skip to content

feat: preserve field declaration order in JSON output#868

Draft
vivainio wants to merge 4 commits intogoogle:masterfrom
vivainio:master
Draft

feat: preserve field declaration order in JSON output#868
vivainio wants to merge 4 commits intogoogle:masterfrom
vivainio:master

Conversation

@vivainio
Copy link
Copy Markdown

@vivainio vivainio commented Apr 2, 2026

This is a DRAFT pull request for information only. See also: https://github.com/vivainio/go-jsonnet-fork

Adds opt-in support for preserving field declaration order in JSON output. The default behavior (alphabetical sorting) is unchanged.

Usage

CLI:

jsonnet --preserve-field-order file.jsonnet

Go API:

vm := jsonnet.MakeVM()
vm.PreserveFieldOrder = true

Implementation

The object model tracks declaration order throughout:

  • simpleObject gains a fieldOrder []string field populated during AST evaluation
  • restrictedObject gains retainedOrder []string
  • uncachedObjectFieldsOrder traverses the object hierarchy to produce ordered field names
  • For extended objects (A + B), left fields come first, then new fields from the right
  • Object comprehensions preserve insertion order
  • manifestJSON returns a jsonOrderedObject (keys + fields map) instead of map[string]interface{}
  • At serialization time, keys are sorted unless preserveFieldOrder is set
  • Native function arguments are flattened to standard map[string]interface{} via flattenJSONForNative

Addresses the requirements raised in #222 and google/jsonnet#407.

vivainio added 4 commits April 2, 2026 21:30
Objects now emit fields in source declaration order rather than
sorted alphabetically. Extended objects (A + B) emit left fields
first, then new fields from the right. Object comprehensions
preserve insertion order.

Implementation:
- simpleObject gains a fieldOrder []string field
- restrictedObject gains retainedOrder []string
- uncachedObjectFieldsOrder traverses the hierarchy for ordered keys
- manifestJSON returns jsonOrderedObject instead of map[string]interface{}
- serializeJSON and manifestAndSerializeMulti handle jsonOrderedObject
- Native function args flattened via flattenJSONForNative

Fix typo extVat -> extVar in TestExtReset (was masked by old alpha order).
…-order

Default behavior reverts to alphabetical sorting (backward compatible
with upstream). Pass --preserve-field-order on the CLI or set
vm.PreserveFieldOrder = true in the API to get declaration order.

The field order tracking in the object model is retained regardless,
so switching between modes is cheap (just sort the already-collected
keys at serialize time).
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