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

How do I sort a possibly-absent array with jq?

给出以下 JSON:

{
  "alice": { "items": ["foo", "bar"] },
  "bob": { "items": ["bar", "foo"] },
  "charlie": { "items": ["foo", "bar"] }
}

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

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

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

,这会崩溃
{
  "alice": { "items": ["foo", "bar"] },
  "bob": { "items": ["bar", "foo"] },
  "charlie": {}
}

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

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

如何获得以下内容?

$ jq < users.json SOMETHING
[
  {
    "items": [
      "bar",
      "foo"
    ]
  },
  {
    "items": [
      "bar",
      "foo"
    ]
  },
  {
    "items": [
    ]
  }
]

我试过使用 // [],但我不确定如何进行排序。

啊哈,这似乎有效:

$ jq < users.json 'map(.items |= (. // [])) | map(.items |= sort)'

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

map_values(if has("items") then .items |= sort else . end)

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

map_values(.items |= (. // [] | sort))