jq是一个操作json的非常好的工具,这里记录一下使用jq去重踩到的一个坑
admin@pc-1:~$ cat raw_0.json
{
"cid": 100,
"info": {
"desc": "this is 100",
"color": "green"
}
}
{
"cid": 200,
"info": {
"desc": "this is 200",
"color": "red"
}
}
{
"cid": 100,
"info": {
"desc": "this is 100",
"color": "green"
}
}
admin@pc-1:~$
admin@pc-1:~$ jq -s 'unique_by(.cid)' raw_0.json
[
{
"cid": 100,
"info": {
"desc": "this is 100",
"color": "green"
}
},
{
"cid": 200,
"info": {
"desc": "this is 200",
"color": "red"
}
}
]
admin@pc-1:~$
admin@pc-1:~$ cat raw_1.json
[
{
"cid": 100,
"info": {
"desc": "this is 100",
"color": "green"
}
},
{
"cid": 200,
"info": {
"desc": "this is 200",
"color": "red"
}
},
{
"cid": 100,
"info": {
"desc": "this is 100",
"color": "green"
}
}
]
admin@pc-1:~$
admin@pc-1:~$ jq -s 'unique_by(.cid)' raw_1.json
jq: error (at raw_1.json:23): Cannot index array with string "cid"
admin@pc-1:~$
admin@pc-1:~$ jq 'unique_by(.cid)' raw_1.json
[
{
"cid": 100,
"info": {
"desc": "this is 100",
"color": "green"
}
},
{
"cid": 200,
"info": {
"desc": "this is 200",
"color": "red"
}
}
]
admin@pc-1:~$
admin@pc-1:~$ jq -h | grep "\-s "
-s read (slurp) all inputs into an array; apply filter to it;
admin@pc-1:~$
admin@pc-1:~$ cat raw_1.json | jq '.[]'
{
"cid": 100,
"info": {
"desc": "this is 100",
"color": "green"
}
}
{
"cid": 200,
"info": {
"desc": "this is 200",
"color": "red"
}
}
{
"cid": 100,
"info": {
"desc": "this is 100",
"color": "green"
}
}
admin@pc-1:~$