Added custom sort map example

This commit is contained in:
Mike Farah 2022-10-17 15:03:47 +11:00
parent d16ee386d2
commit 6db7acbf69
4 changed files with 35 additions and 0 deletions

View File

@ -107,6 +107,26 @@ KEY_a: 1
KEY_b: 2
```
## Custom sort map keys
Use to_entries to convert to an array of key/value pairs, sort the array using sort/sort_by/etc, and convert it back.
Given a sample.yml file of:
```yaml
a: 1
c: 3
b: 2
```
then
```bash
yq 'to_entries | sort_by(.key) | reverse | from_entries' sample.yml
```
will output
```yaml
c: 3
b: 2
a: 1
```
## Use with_entries to filter the map
Given a sample.yml file of:
```yaml

View File

@ -11,3 +11,6 @@ diff file1.yml file2.yml
```
Note that `yq` does not yet consider anchors when sorting by keys - this may result in invalid yaml documents if your are using merge anchors.
For more advanced sorting, using `to_entries` to convert the map to an array, then sort/process the array as you like (e.g. using `sort_by`) and convert back to a map using `from_entries`.
See [here](https://mikefarah.gitbook.io/yq/operators/entries#custom-sort-map-keys) for an example.

View File

@ -12,6 +12,9 @@ diff file1.yml file2.yml
Note that `yq` does not yet consider anchors when sorting by keys - this may result in invalid yaml documents if your are using merge anchors.
For more advanced sorting, using `to_entries` to convert the map to an array, then sort/process the array as you like (e.g. using `sort_by`) and convert back to a map using `from_entries`.
See [here](https://mikefarah.gitbook.io/yq/operators/entries#custom-sort-map-keys) for an example.
{% hint style="warning" %}
Note that versions prior to 4.18 require the 'eval/e' command to be specified. 

View File

@ -52,6 +52,15 @@ var entriesOperatorScenarios = []expressionScenario{
"D0, P[], (!!map)::KEY_a: 1\nKEY_b: 2\n",
},
},
{
description: "Custom sort map keys",
subdescription: "Use to_entries to convert to an array of key/value pairs, sort the array using sort/sort_by/etc, and convert it back.",
document: `{a: 1, c: 3, b: 2}`,
expression: `to_entries | sort_by(.key) | reverse | from_entries`,
expected: []string{
"D0, P[], (!!map)::c: 3\nb: 2\na: 1\n",
},
},
{
skipDoc: true,
document: `{a: 1, b: 2}`,