Given the following JSON:
{
"alice": { "items": ["foo", "bar"] },
"bob": { "items": ["bar", "foo"] },
"charlie": { "items": ["foo", "bar"] }
}
I can sort the items
array as follows:
$ jq < users.json 'map(.items |= sort)'
[
{
"items": [
"bar",
"foo"
]
},
{
"items": [
"bar",
"foo"
]
},
{
"items": [
"bar",
"foo"
]
}
]
However, this crashes if any user doesn't have items
:
{
"alice": { "items": ["foo", "bar"] },
"bob": { "items": ["bar", "foo"] },
"charlie": {}
}
Trying to sort it gives an error.
$ jq < users.json 'map(.items |= sort)'
jq: error (at <stdin>:5): null (null) cannot be sorted, as it is not an array
How can I obtain the following?
$ jq < users.json SOMETHING
[
{
"items": [
"bar",
"foo"
]
},
{
"items": [
"bar",
"foo"
]
},
{
"items": [
]
}
]
I've tried using // []
but I'm not sure how to do this in relation to sorting.