expr icon indicating copy to clipboard operation
expr copied to clipboard

How to access to a field with dot in its key?

Open zhnpeng opened this issue 6 years ago • 9 comments

Hi, How to access to a field with dot in its key? Example:

package main

import (
	"fmt"
	"github.com/antonmedv/expr"
)

func main() {
	env := map[string]interface{}{
		"User.Message": "Hi Johny",
	}

	code0 := "User.Message"
	code1 := "User\.Message"

	_, err := expr.Eval(code0, env)
	if err != nil {
		fmt.Println(err)
	}
	
	_, err = expr.Eval(code1, env)
	if err != nil {
		fmt.Println(err)
	}
}

Output:

cannot fetch Message from <nil> (1:6)
 | User.Message
 | .....^
unrecognized character: U+005C '\' (1:6)
 | User\.Message
 | .....^

Thanks for replying

zhnpeng avatar Apr 07 '20 14:04 zhnpeng

Use something like this:

package main

import (
	"fmt"
	"github.com/antonmedv/expr"
)

func main() {
	env := map[string]interface{}{
		"User.Message": "Hi Johny",
	}
	env["$"] = env

	code0 := `$["User.Message"]`

	out, err := expr.Eval(code0, env)
	if err != nil {
		fmt.Println(err)
	}
	
	fmt.Println(out)
}

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

antonmedv avatar Apr 07 '20 15:04 antonmedv

Use something like this:

package main

import (
	"fmt"
	"github.com/antonmedv/expr"
)

func main() {
	env := map[string]interface{}{
		"User.Message": "Hi Johny",
	}
	env["$"] = env

	code0 := `$["User.Message"]`

	out, err := expr.Eval(code0, env)
	if err != nil {
		fmt.Println(err)
	}
	
	fmt.Println(out)
}

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

env stack overflow....

Neyzoter avatar Oct 25 '21 06:10 Neyzoter

Is there any other way to access a field with a dot on it without adding a new key?

joaobologna avatar Oct 28 '22 16:10 joaobologna

I’m thinking on adding special variable like global.

antonmedv avatar Oct 28 '22 17:10 antonmedv

something likeglobal["my.identifier"]?

joaobologna avatar Oct 28 '22 18:10 joaobologna

Yes, or env["foo.bar"]. But need to figure out what is the best way.

Maybe?

@["foo-bar"]

antonmedv avatar Oct 28 '22 18:10 antonmedv

I like @ better. env seems more related to the "complete" variable rather than suggesting "where to look for the data", which would be the root of it. Also, users can use other variable names for env.

joaobologna avatar Oct 28 '22 19:10 joaobologna

@antonmedv Just hit this issue. My key is smth like: foo{"bar"} == 777. But it returns unexpected token Identifier("bar"). If I escape "s with \"s, it evaluates but expr.Run returns false without any errors. Since the actual value is 0 in the initial state, I'd expect fail instead. :/

Dentrax avatar Dec 24 '22 20:12 Dentrax

Done.

Now expr supports env keyword. https://expr.medv.io/docs/Language-Definition#env-variable

antonmedv avatar Aug 12 '23 13:08 antonmedv