gjson
gjson copied to clipboard
Unclear Outputs with AddModifier
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)
})
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
Thanks for the example. The behavior of this is a bit unusual (possibly a bug?): https://play.golang.org/p/14ScdPIcAHS
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