Sree
Sree

Reputation: 351

How to validate Sub-Sets of JSON Keys using match contains when there are nested JSON's in the response

From a response, I extracted a subset like this.

{
  "base": {
    "first": {
      "code": "1",
      "description": "Its First"
    },
    "second": {
      "code": "2",
      "description": "Its Second"
    },
    "default": {
      "last": {
        "code": "last",
        "description": "No"
      }
    }
  }
}

If I need to do a single validation using And match X contains to check

  1. Inside first the Code is 1
  2. Inside default-last the code is last?

Instead of using json path for every validation, I am trying to extract a specific portion and validate it. If there is no nested json paths, I can do it very easily using And match X contains, however when there are nested jsons, I am not able to do it.

Upvotes: 1

Views: 1223

Answers (2)

Peter Thomas
Peter Thomas

Reputation: 58153

Does this work for you:

* def first = get[0] response..first
* match first.code == '1'
* def last = get[0] response..default.last
* match last.code == 'last'

Edit: ok looks like you want to condense into one line as far as possible, more importantly to be able to do contains in nested nodes. Personally, I find this sometimes to be not worth the trouble, but here goes.

Refer also to these short-cuts: https://github.com/intuit/karate#contains-short-cuts

* def first = { code: "1" }
* match response.base.first contains first
* match response.base contains { first: '#(^first)' }
* def last = { code: 'last' }
* match response.base contains { first: '#(^first)', default: { last: '#(^last)' } }

Upvotes: 1

Sree
Sree

Reputation: 351

Mhmm, My question is slightly different I think. For example if I directly point to the first using a json path and save it to a variable savedResponse, I can do this validation

And match savedResponse contains {code: "1"}

If there were 10 Key value combinations under first and if I need to validate 6 of those, I can use the same json path and I can easily do it using match contains

Similiar way if I save the above response to a variable savedResponse, how I can validate mutliple things using match contains, in this. The below statement will not work anyway.

And match savedResponse contains {first:{code:"1"}, last:{code:"last"}}

However if I modify something will it work?

Upvotes: 1

Related Questions