Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JQ: Modify object that is the result of a filter while keeping the original structure

I have the following JSON

Original Data

{
  "myValues": [
    {
      "filterableValue": "x",
      "something": "else"
    },
    {
      "filterableValue": "y",
      "another key": "another value"
    },
    {
      "filterableValue": "z"
    }
  ],
  "foo": "bar"
}

Using JQ I want to add a key value pair to the first (or all) entries in the myValues array, that have the filterableValue=="y". The position/index of these entries inside the myValues array is arbitrary.

Expected Output

The result should have the same structure (still contain both foo and myValues) but have a modified entry where filterableValue=="y".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "myValues": [
    {
      "filterableValue": "x",
      "something": "else"
    },
    {
      "filterableValue": "y",
      "another key": "another value",
      "this": "has been added" // <-- this is the only thing that changed
    },
    {
      "filterableValue": "z"
    }
  ],
  "foo": "bar"
}

What I tried and why it failed

So far I managed to filter the respective array entry and set the value on the filtered output but didn’t manage to keep the original structure AND modifiy a filtered entry.
My JQ that adds the "this":"has been added" pair but does not contain the original structure is:

.myValues|map(select(.filterableValue=="y"))[0]|.this="has been added"
jqplay mwe

Question

How can I modify a filtered entry as above and contain the original structure?

>Solution :

Enclose the whole selector on the LHS within parentheses:

(.myValues[] | select(.filterableValue == "y")).this = "has been added"

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading