cli: option -k to preserve the order of keys #239
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.
I read feedback on #189 and #84 and implemented it in a way that does not change
gojq
(the library). Also it is completely optional and it only affects encoding and decoding. Everything in between is the same. Still it covers majority of myjq
uses: pretty printing, extraction by path. Maps in JSON are often Go structs and preserving the order improves readability a lot.It builds an external map from object pointer to the list of keys as seen in the input. If an object does not change during the whole operation of gojq, cli can find the original order of keys during encoding by looking into the map and checking if the set of keys is the same. This works for both JSON and YAML.
go-ordered-map is used as an intermediate object created during decoding and encoding (in case of YAML). After parsing is done, the list of keys is extracted from orderedmap and the map is turned into a regular
map[string]any
. A pointer to that map is added to a global tablemap[uintptr][]string
which stores the order of keys. When encoding, this data is used to put keys in the right order.Example: