Forum Discussion

smartbear90211's avatar
smartbear90211
Occasional Contributor
10 years ago

JSONPath Expression to assert a list contains a specific element

I'm looking for an expression which checks if an element with id=123 is contained in a json-list. 

 

[
      {
      "id": "123"
      }
   },
      {
      "id": "456"
      }
   }
]

 Given the above list, I could use this JSONPath Expression: $[0].id but unfortunately, I can't guarantee that the element is always at index 0. Sometimes it would be $[1].id.

I tried with $[*].id but this extracts [[id1,id2]].

 

So basically, I'm looking for something like "is 123 equals to $[0].id OR $[1].id" or if that's not possible something like "does $[*].id contains an element "123". 

 

I'm using ReadyApi 1.4.1.

 

  • marcl's avatar
    marcl
    Occasional Contributor

    I think you're looking for something like this:

    $[?(@.id == 123)].id
  • nmrao's avatar
    nmrao
    Icon for Champion Level 2 rankChampion Level 2

    Not very good at Json path.

    But below script assertion should do the job[using the assumed json array]

     

     

    import net.sf.json.groovy.JsonSlurper

    def jsonText = '''{ "cars": [ { "name" : "Jetta", "madeBy" : "Volkswagen" }, { "name" : "Polo GT", "madeBy" : "Volkswagen" }, { "name" : "i30", "madeBy" : "Hyundai" } ] }''' def jsonSlurper = new JsonSlurper() def cars = jsonSlurper.parseText(jsonText).cars def expectedName = 'Jetta' // You may use test case propperty here if you wish def expectedValueExists=false if (cars) { cars.each{if (it.name==expectedName) {expectedValueExists=true} } } if (expectedValueExists) { log.info "Expected car ${expectedName} exists"} assert expectedValueExists, "Expected car name does not exists"

     

    Hope this is helpful