gjson icon indicating copy to clipboard operation
gjson copied to clipboard

Unclear Outputs with AddModifier

Open jshlbrd opened this issue 3 years ago • 3 comments

I'm trying to add a simple modifier to overwrite a value with a static string, but the output is always "true". Can you help me understand the correct way to use AddModifier? Given the examples I've seen, I don't understand why this does not work:

func modStatic(json, arg string) string {
	return arg
}

gjson.AddModifier("static", func(json, arg string) string {
		return modStatic(json, arg)
	  })

jshlbrd avatar Mar 01 '21 16:03 jshlbrd

Here's another example using a modifier named @static that replaces out json that equals "world" with the value true.

package main

import "github.com/tidwall/gjson"

func main() {
	gjson.AddModifier("static", func(json, arg string) string {
		if gjson.Parse(json).String() == "world" {
			return arg
		}
		return json
	})
	json := `{"hello":"world","howdy":"planet"}`
	println(gjson.Get(json, `howdy.@static:true`).Raw)
	println(gjson.Get(json, `hello.@static:true`).Raw)
}
// Output:
// "planet"
// true

https://play.golang.org/p/s-WNJjSityu

tidwall avatar Mar 02 '21 00:03 tidwall

Thanks for the example. The behavior of this is a bit unusual (possibly a bug?): https://play.golang.org/p/14ScdPIcAHS

jshlbrd avatar Mar 02 '21 01:03 jshlbrd

I think the issue is that the argument should be a valid json value. In your case you’ll probably need to add quotation marks around each arg.

https://play.golang.org/p/Y3ATaEDW0LF

tidwall avatar Mar 02 '21 03:03 tidwall