如何使用 jq 对可能不存在的数组进行排序?

Wil*_*hes 5 arrays sorting json edit jq

给定以下 JSON:

{
  "alice": { "items": ["foo", "bar"] },
  "bob": { "items": ["bar", "foo"] },
  "charlie": { "items": ["foo", "bar"] }
}
Run Code Online (Sandbox Code Playgroud)

我可以items按如下方式对数组进行排序:

$ jq < users.json 'map(.items |= sort)'
[
  {
    "items": [
      "bar",
      "foo"
    ]
  },
  {
    "items": [
      "bar",
      "foo"
    ]
  },
  {
    "items": [
      "bar",
      "foo"
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

但是,如果任何用户没有items

{
  "alice": { "items": ["foo", "bar"] },
  "bob": { "items": ["bar", "foo"] },
  "charlie": {}
}
Run Code Online (Sandbox Code Playgroud)

尝试对其进行排序会出错。

$ jq < users.json 'map(.items |= sort)'
jq: error (at <stdin>:5): null (null) cannot be sorted, as it is not an array
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得以下内容?

$ jq < users.json SOMETHING
[
  {
    "items": [
      "bar",
      "foo"
    ]
  },
  {
    "items": [
      "bar",
      "foo"
    ]
  },
  {
    "items": [
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

我尝试过使用// [],但我不确定如何执行与排序相关的操作。

Jef*_*ado 5

如果使用 映射对象的值,则可以保留原始结构map_values。然后从那里开始,如果您想保留 items 数组的缺失,只需事先检查它即可。

map_values(if has("items") then .items |= sort else . end)
Run Code Online (Sandbox Code Playgroud)

否则,如果您不关心添加空项目:

map_values(.items |= (. // [] | sort))
Run Code Online (Sandbox Code Playgroud)