bkd*_*kdm 2 sorting json unique jq
我有如下所示的 json:
% cat example.json
{
"values" : [
{
"title": "B",
"url": "https://B"
},
{
"title": "A",
"url": "https://A"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我想根据标题对值进行排序。即预期输出
{
"title": "A",
"url": "https://A"
}
{
"title": "B",
"url": "https://B"
}
Run Code Online (Sandbox Code Playgroud)
尝试了一下打击。不起作用:
% jq '.values[] | sort' example.json
jq: error (at example.json:12): object ({"title":"B...) cannot be sorted, as it is not an array
% jq '.values[] | sort_by(.title)' example.json
jq: error (at example.json:12): Cannot index string with string "title"
Run Code Online (Sandbox Code Playgroud)
如果你想保留整体结构,你可以使用 jq 过滤器:
.values |= sort_by(.title)
Run Code Online (Sandbox Code Playgroud)
如果您想提取 .values 并对数组进行排序,请省略“=”:
.values | sort_by(.title)
Run Code Online (Sandbox Code Playgroud)
产生如 Q 所示的输出:
.values | sort_by(.title)[]
Run Code Online (Sandbox Code Playgroud)
定义“唯一性”的方法有多种,实现唯一性的方法也有多种。
一种选择就是使用unique_by而不是sort_by; 另一种(具有不同的语义)是使用(sort_by(.title)|unique)而不是sort_by(.title).
| 归档时间: |
|
| 查看次数: |
3442 次 |
| 最近记录: |