Issue
I have a JSON data like below
[
{
"id": 4449282,
"iid": 6316,
"project_id": 1234,
"sha": "abcdefg",
"ref": "test_branch",
"status": "running",
"source": "web",
"created_at": "2023-09-25T05:55:20.788Z",
"updated_at": "2023-09-25T05:55:23.481Z",
"web_url": "https://example.gitlab.com"
}
]
I want the output to be filtered only with select key and values. The filtered output I need is
[
{
"iid": 6316,
"project_id": 1234,
"ref": "test_branch",
"status": "running",
"source": "web",
"created_at": "2023-09-25T05:55:20.788Z",
"updated_at": "2023-09-25T05:55:23.481Z",
"web_url": "https://example.gitlab.com"
}
]
I tried with jq 'with_entries
and jq select
, but couldn't get it working.
Solution
If you want to provide what to keep, you can use the pick
filter if you have jq 1.7:
map(pick(
.iid, .project_id, .ref, .status, .source,
.created_at, .updated_at, .web_url
))
If you don't have jq 1.7, you can define it by copying it over from the source:
def pick(pathexps):
. as $in | reduce path(pathexps) as $a (null;
setpath($a; $in|getpath($a))
);
map(pick(…))
If you rather want to provide what to delete, use del
instead:
map(del(.id, .sha))
As you've tried using with_entries
and select
, here's how you could achieve the desired result using these filters:
Selecting what to keep:
map(with_entries(select(.key | IN(
"iid", "project_id", "ref", "status", "source",
"created_at", "updated_at", "web_url"
))))
Selecting what not to keep:
map(with_entries(select(.key | IN("id", "sha") | not)))
All of the above output:
[
{
"iid": 6316,
"project_id": 1234,
"ref": "test_branch",
"status": "running",
"source": "web",
"created_at": "2023-09-25T05:55:20.788Z",
"updated_at": "2023-09-25T05:55:23.481Z",
"web_url": "https://example.gitlab.com"
}
]
Answered By - pmf Answer Checked By - David Goodson (WPSolving Volunteer)