简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM