Referring to Self '$' in Embedded Expressions in Karate

Viewed 47

probably a silly question. I am trying to make use of self '$' when defining/reading a json.

  * def x = {a:1,b:{c:'#($.a)'},d:2}
  * print x

It fails.

"a": 1,
  "b": {
    "c": "#($.a)"
  },
  "d": 2
}

Is it possible to do something like above? At the time of defining variable, when the compiler reaches 'c', 'a' has already been defined. So, I am hopeful that it might be possible.

But I do understand there are edge cases of cyclic reference (referring '$') or referring something that is not yet defined('$.d'), but those cases can be handled to throw exception.

1 Answers

Yes, the $ magic variable is designed only for use within a match, like this:

* def x = { a: 1, b: { c: 1 }, d: 2 }
* match x contains { b: { c: '#($.a)' } }

That said, maybe you should do this:

* def val = 1
* def x = { a: '#(val)', b: { c: '#(val)' }, d: 2 }
* match x == { a: 1, b: { c: 1 }, d: 2 }

Note that you can always "build" JSON using JS snippets like this:

* def x = { a: 1, d: 2 }
* x.b = { c: x.a }
* match x == { a: 1, b: { c: 1 }, d: 2 }
Related