EN VI

In jq, how to select the desired properties at all levels?

2024-03-14 06:00:09
In jq, how to select the desired properties at all levels?

It seems a pretty basic need, but I can't find it in the tutorial

Imagine we got an object like:

{"data":[
  {"prop1":"a", "prop2":"b", "prop3":"c", "prop4":"d", "nestedprops":{"nestedprop1":"A","nestedprop2":"B"} },
  {"prop2":"b", "prop3":"c", "nestedprops":{"nestedprop1":"A"}},
  {"prop3":"c"}
]}

I just want the exact same json, but filtering out prop3,prop4 and nestedprop2, or in other words, I want to filter in the whole tree for prop1, prop2 and nestedprop1

{"data":[
  {"prop1":"a", "prop2":"b", "nestedprops":{"nestedprop1":"A"} },
  {"prop2":"b", "nestedprops":{"nestedprop1":"A"}},
  {}
]}

I'm trying with jq '.data[] | {prop1,prop2,nestedprops:{nestedprop1}}' and the like but I can't find it

Solution:

I just want the exact same json, but filtering out prop3,prop4 and nestedprop2

Update each item in the array by deleting what you want to be filtered out:

.data[] |= del(.prop3, .prop4, .nestedprops.nestedprop2)

Demo

I want to filter in the whole tree for prop1, prop2 and nestedprop1

Update each item by picking what you need. Filter for non-null values using values, and default to an empty object using //.

.data[] |= (pick(.prop1, .prop2, .nestedprops.nestedprop1 | values) // {})

Demo

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login