Issue
I have this json string :
{
"head": {
"url": "foobar;myid=E50DAA932C22739F92BB250C14365440"
}
}
With jq on the shell I get the content of url
as an array:
jq -r '.head.url | split(";")[] '
This returns:
foobar
myid=E50DAA932C22739F92BB250C14365440
My goal is to get the id (E50DA...) after =
only. I could simply use [1]
to get the second element and then use a regex to get the part after the =
.
But the order of elements is not safe and I'm sure there's a better way with jq already that I dont know of. Maybe create a map of the elements and use myid
as a key to get the value (E50...)?
Thank you for your input!
Solution
Do you have to do it with jq
only? You could further process the output with grep
and cut
:
jq '.head.url | split(";")[]' | grep '^myid=' | cut -d= -f2
But alas, it is easily possible by first building an object from the key value pairs and then look up the value for the key in question:
.head.url
| split(";")
| map(split("=") | { key: .[0], value: .[1] })
| from_entries
| .myid
equivalent to:
.head.url
| split(";")
| map(split("=") | { key: .[0], value: .[1] })
| from_entries["myid"]
Or without building an object, simply by selecting the first array item with matching key, then outputting its value:
.head.url | split(";")[] | split("=") | select(first == "myid")[1]
NB. x | split(y)
can be expressed as x/y
, e.g. .head.url/"@"
.
Answered By - knittl Answer Checked By - Gilberto Lyons (WPSolving Admin)