2

I'm trying to fetch the value from an attribute in the payload but Karate throws an error or simply doesn't fetch the value.

I've created a simplified version of my code to make it easier to understand.

* def lists = [{@id: 1, type: 'video'}, {@id: 2, type: 'image'}]
* def ser = {@id: 2, type: '#string'}

* def foundAt = []
* def fun = function(x, i){ if (karate.match(x, ser).pass) foundAt.add(i) }
* eval karate.forEach(lists, fun)
* def storeId = lists[foundAt[0]].@id
* def storeType = lists[foundAt[0]].type
* print storeId
* print storeType

print storeType will print the value as expected but print storeId will print the following error message:

javascript evaluation failed: lists[foundAt[0]].@id, <eval>:1:18 Expected ident but found error
lists[foundAt[0]].@id
                  ^ in <eval> at line number 1 at column nu*mber 18

I expect the value '2' to be printed but clearly I'm doing something wrong?

1 Answer 1

1

One small change will do the trick since @ is a "bad" character for JSON key-names:

* def storeId = lists[foundAt[0]]['@id']

Here's also a suggested simplification to your code:

* def fun = function(x, i){ return karate.match(x, ser).pass }
* def found = karate.filter(lists, fun)
* def storeId = found[0]['@id']
* def storeType = found[0].type
* print storeId
* print storeType
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.