I have a array that looks like this:
[
{
"id": 1,
"version": "2.3.4"
},
{
"id": 2,
"version": "1.4.4"
},
{
"id": 3,
"version": "0.0.4"
},
{
"id": 4,
"version": "1.3.4"
},
]
And I need to get all the objects where the version is "1.2.0".
I am interested in a built in way using JQ but I cannot find anything related. Maybe it does not exist?
I know I could do some ugly regex hack here, but what would be the right way to solve this so I can easily swap my condition so if instead of 1.2.0 maybe in a short time in the future lets say I want the objects with version greater than 1.2.7 for instance?
3
Answers
You always have the option of parsing and implementing the comparisons. Make it as robust as needed.
Then utilize the new comparison function:
If you need to get all the objects where the version is "1.2.0", you can use string comparison :
If you want the objects with version greater than 1.2.7, then:
You could also use a simple regex hack if the semver strings do not need to be checked for correctness. For example, consider the following:
Since a valid semver string always has three components, none of which can have superfluous leading zeros, and since jq’s built-in ordering is so friendly (as per the comment by @A.H.),
semver
as defined above should make it quite easy to compare valid semver strings. However, since the spec requires that "pre-release" < "release", for non-trivial semantic version strings, some care is required:Since your example only has trivial semver specs, we could get away with:
Caveat: I’m no expert on semantic versioning, and it’s quite likely the above needs some improvement. Tweak suggestions would be welcome.