Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot index into static array or object #115

Open
chetbox opened this issue Feb 3, 2022 · 4 comments
Open

Cannot index into static array or object #115

chetbox opened this issue Feb 3, 2022 · 4 comments
Labels

Comments

@chetbox
Copy link

chetbox commented Feb 3, 2022

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
Copy link
Author

chetbox commented Feb 3, 2022

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
Copy link
Owner

TomFrost commented Feb 3, 2022

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

@TomFrost TomFrost added the bug label Feb 3, 2022
@chetbox
Copy link
Author

chetbox commented Feb 4, 2022

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
Copy link

ablsc commented Jun 7, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants