TomFrost / Jexl

Javascript Expression Language: Powerful context-based expression parser and evaluator
MIT License
559 stars 90 forks source link

Cannot index into static array or object #115

Open chetbox opened 2 years ago

chetbox commented 2 years ago

Hi! Thanks for this great library!

I just came across something I had assumed would work but it doesn't seem to.

["zero", "one", "two", "three"][1]

(Playground link)

Gives this error:

Error: Token [ (openBracket) unexpected in expression: ["zero", "one", "two", "three"][

Similarly,

{foo: 1}['foo']

(Playground link)

Gives this error:

Error: Token [ (openBracket) unexpected in expression: {foo: 1}[

It's possible to index into and array or an object if it's part of the Jexl context but seemingly not statically like this.

chetbox commented 2 years ago

Some context for this is I'm trying to write an expression that give me a random string from a static list.

["One","Two","Three"][(random() * 3) | floor]

Am I going about this the wrong way?

TomFrost commented 2 years ago

Oh wow -- I see why that's happening. Definitely a bug!

Until this is fixed, you could throw this into a transform function:

jexl.addTransform('random', (ary) => {
  const idx = Math.floor(Math.random() * ary.length)
  return ary[idx]
})

Now your expression becomes ['one', 'two', 'three']|random

chetbox commented 2 years ago

Until this is fixed, you could throw this into a transform function:

jexl.addTransform('random', (ary) => {
  const idx = Math.floor(Math.random() * ary.length)
  return ary[idx]
})

This will do for now. Thanks!

ablsc commented 1 year ago

To avoid raising duplicate issues it looks as if what chetbox has raised means static JSON as parameters to functions isn't currently possible with jexl right now.

The following expression

"aFunction(aVariable, { \"aProperty\": 1 })"

raises the error

Error: Token "aProperty" (literal) unexpected in expression: aFunction(aVariable, { "aProperty"

By changing the expression to the following and parsing the string in aFunction as JSON does work

"aFunction(aVariable, \"{ \\\"aProperty\\\": 1 }\")"

I wondered if transforms might help but parsing bombs out just the same.