gojq icon indicating copy to clipboard operation
gojq copied to clipboard

Custom @escape functions

Open myaaaaaaaaa opened this issue 1 year ago • 4 comments

Something like this?

gojq.Compile(
	query,
	gojq.WithEscaper("goprint", func(x any) string {
		return fmt.Sprint(x)
	}),
)
$ "abcde" | split("") |
	@json    "json:    \(.)",
	@sh      "sh:      \(.)",
	@goprint "goprint: \(.)"

json:    ["a","b","c","d","e"]
sh:      'a' 'b' 'c' 'd' 'e'
goprint: [a b c d e]

myaaaaaaaaa avatar Dec 20 '24 19:12 myaaaaaaaaa

For reference, jaq implements it like this:

$ jaq -n 'def @upcase: ascii_upcase; "world" | @upcase "hello \(.)"'
"hello WORLD"

wader avatar Dec 20 '24 23:12 wader

For reference, jaq implements it like this:

$ jaq -n 'def @upcase: ascii_upcase; "world" | @upcase "hello \(.)"'
"hello WORLD"

Pretty cool - although at that point, I think we may as well just redefine the @foo syntax to be syntactic sugar for a normal function call:

-"world" | @upcase "hello \(.)"
+"world" | "hello \(. | upcase)"

myaaaaaaaaa avatar Dec 20 '24 23:12 myaaaaaaaaa

@myaaaaaaaaa now jqjq does it the same way at jaq 🥳 but as you say even more general would be nice but then would we extend the the standard library with all the existing formats as functions minus the "@"? 🤔

wader avatar Dec 25 '24 10:12 wader

but then would we extend the the standard library with all the existing formats as functions minus the "@"? 🤔

Yes, that would be one of the pitfalls of this method - mainly the redundant text - tostring and json - tojson functions.

myaaaaaaaaa avatar Dec 25 '24 23:12 myaaaaaaaaa