json manipulation via command line

Asked

Viewed 53 times

0

I’m using the jq to manipulate json via command line.

Having as input a json obtained via gitlab api:

[
  {
    "id": 001,
    "description": "Uma descrição teste",
    "ssh_url_to_repo": "[email protected]:shazam/dc.git",
    "created_at": "2019-04-22T19:55:04.851Z",
    "last_activity_at": "2019-04-24T17:09:28.217Z"
  },
  {
    "id": 002,
    "description": "Uma descrição teste",
    "ssh_url_to_repo": "[email protected]:marvel/marvel.git",
    "created_at": "2019-04-22T19:55:04.851Z",
    "last_activity_at": "2019-04-23T17:09:28.217Z"
  },
  {
    "id": 003,
    "description": "Uma descrição teste",
    "ssh_url_to_repo": "[email protected]:one/piece.git",
    "created_at": "2019-04-22T19:55:04.851Z",
    "last_activity_at": "2019-04-22T17:09:28.217Z"
  }
]

I run the following command:

if .[].ssh_url_to_repo | contains("one/piece") then .[] | .last_activity_at else false end

And get the following output:

false
false
"2019-04-24T17:09:28.217Z"
"2019-04-23T17:09:28.217Z"
"2019-04-22T17:09:28.217Z"

I wanted the date just when he finds one ssh which contains the substring one/piece. However, when he finds this substring he prints the date of all objects.

What am I doing wrong?

What other tool besides the jq I can use to manipulate json?

1 answer

0

(Test with the usual jq 'programa' f.json)

Try something like selecting the ones that matter:

.[] | select(.ssh_url_to_repo | contains("one/piece")).last_activity_at

Another alternative would be map(select(cond).campo ):

map(select(.ssh_url_to_repo | contains("one/piece")).last_activity_at)

To get the fakes as they appear in your version:

map(if .ssh_url_to_repo | contains("one/piece") then  .last_activity_at else false end)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.