Wil*_*hes 5 arrays sorting json edit 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": [
    ]
  }
]
我尝试过使用// [],但我不确定如何执行与排序相关的操作。
如果使用 映射对象的值,则可以保留原始结构map_values。然后从那里开始,如果您想保留 items 数组的缺失,只需事先检查它即可。
map_values(if has("items") then .items |= sort else . end)
否则,如果您不关心添加空项目:
map_values(.items |= (. // [] | sort))