Tanvi Jaywant
Tanvi Jaywant

Reputation: 415

How to filter based on value in json using JQ

{    "amazon": {

                "items": [
                  {
                    "name": "harry potter",
                    "state": "sold"
                  },
                  {
                    "name": "adidas shoes",
                    "state": "in inventory"
                  },
                  {
                    "name": "watch",
                    "state": "returned"
                  },
                 ]
    }

}

I want to write jq json parsing tool to modify "name:harry potter" from state "sold" to "returned"

I want to modify this in a shell script ( .sh ) file.

Upvotes: 0

Views: 254

Answers (2)

oliv
oliv

Reputation: 13249

Another jq filter using select function:

jq '.amazon.items |= map(select(.name=="harry potter").state="returned")' file

Upvotes: 1

peak
peak

Reputation: 116730

Assuming the input is valid JSON, the following filter will perform the edit conditionally as specified:

.amazon.items
|= map(if .name == "harry potter" and .state == "sold"
       then .state = "returned" else . end)

Or rather, invoking jq with this filter will emit the updated JSON.

You might want to use sponge to overwrite the original file once you're sure that's really what you want to do.

Upvotes: 1

Related Questions