Sid
Sid

Reputation: 33

Bash jq modify json : get and set

I use jq to parse and modify cURL response and it works perfect for all of my requirements except one. I wish to modify a key value in the json, like:

A) Input json

[
    {
        "id": 169,
        "path": "dir1/dir2"
    }
]

B) Output json

[
    {
        "id": 169,
        "path": "dir1"
    }
]

So the last directory is removed from the path. I use the script:

curl --header -X GET -k "${URL}" | jq '[.[] | {id: .id, path: .path_with_namespace}]' | jq '(.[] | .path) = "${.path%/*}"'

The last pipe is ofcourse not correct and this is where I am stuck. The point is to get the path value and modify it. Any help is appreciated.

Upvotes: 0

Views: 321

Answers (1)

chepner
chepner

Reputation: 530930

One way to do this is to use split and join to process the path, and use |= to bind the correct expression to the .path attribute.

... | jq '.[] | .path|=(split("/")[:-1]|join("/"))
  • split("/") takes a string and returns an array
  • x[:-1] returns an array consisting of all but the last element of x
  • join("/") combines the elements of the incoming array with / to return a single string.
  • .path|=x takes the value of .path, feeds it through the filter x, and assigns the resulting value to .path again.

Upvotes: 2

Related Questions