jq: Select property value using regex

Multi tool use
jq: Select property value using regex
I have the following json Object:
{
"foo": {
"name": "Name 1",
"color": "green",
"something_else": {
"name" : "Name 2"
}
},
"bar": {
"name": "Something else",
"color": "red"
}
}
To get all possible parents properties of the property called "name" using jq I tried :
path(recurse|select(.name? !=""))[0]
And it works and give back :
"foo"
"foo"
"bar"
Now I want to apply regex to filter the property value, say I want to consider only all properties called name
that have a value beginning with "Name" and followed by a number like "Name 2"
, to get:
name
"Name 2"
"foo"
"foo"
I tried this:
path(recurse|select(.name? =~ match(/Name */)))[0]
How to use match and how to place it correctly inside the query ?
null
Should your result be just
foo
? why is it repeated?– Inian
Jul 2 at 9:14
foo
1 Answer
1
You could use paths/1
instead of path
because the former ignores null paths. Also with path
you need to add a filter logic to ignore the null
which does not match any of the regex conditions
paths/1
path
path
null
paths(select(.name? | match("Name [0-9]")))[0]
See jq - documetation - paths/1
Is there any way to filter repeated entries
– Amani Ben Azzouz
Jul 2 at 9:34
By the way thank you :) it works
– Amani Ben Azzouz
Jul 2 at 9:34
@AmaniBenAzzouz: Try adding
|unique
to the result from the select
filter– Inian
Jul 2 at 9:37
|unique
select
One last question please , when I try to add a property with no child property called name it throw an error, is there something like
if exists
? try to change bar like this "bar": { "color": "red" }
– Amani Ben Azzouz
Jul 2 at 9:44
if exists
"bar": { "color": "red" }
@AmaniBenAzzouz: I think its a totally new question. It isn't bad if you post a new question with the researches you made
– Inian
Jul 2 at 9:45
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I get an extra
null
result when applying that filter to your json input shown– Inian
Jul 2 at 8:55