In the jq script below I want to print either the concatenation of the first_name
and the last_name
or just the last_name
.
$ echo '{"first_name": "John", "last_name": "Johnson"}' | jq -c '{"name": (if (.last_name | startswith(.first_name)) then .last_name else .first_name +" " + .last_name end)}'
The error is
jq: error (at <stdin>:1): Cannot index string with string "first_name"
The jq command fails in the call to startswith
- as if startswith
only accepted string literals. If I change startswith(.first_name)
to startswith("John")
then the expression compiles and works as expected.
In the real-world example, there is many input records and many different first_name
s. Is there a way I could plug in .first_name
to startswith
?