You've been big help in the past, so I'm hoping you can help me with this. So currently I'm working on a project at work using soapui to get back a giant Json payload. I need to create some assertions, and some of these will need to look at multiple nodes that have only one thing in common. That one thing is the first part of one of the nodes.
So what I'm looking for is some kind of substring command for JSONPath. Here is an example of what I'm looking for.
"BurgerJoints": [
{
"JointName": "Bob's Burgers",
"Price": 5
},
{
"JointName": "Bob's Broiler Stand",
"Price": 5
},
{
"JointName": "Burger King",
"Price": 5
},
{
"JointName": "Bob's Beef Haven",
"Price": 5
},
{
"JointName": "Super Weenie Hut",
"Price": 5
}
]
In my example let's say I'm looking for all joints that are Bob's something. So my initial thought was to do something like BurgerJoints[?(@.Substring(JointName,0,3)=="Bob")] , to give me the nodes. But it looks like it didn't work. Can anyone tell me where my syntax went wrong, or if there isn't a way to do it in that way, what the best to accomplish my goal is?
Thanks guys!!
EDIT:
So I tried using Groovyscript to do it and I think I've gotten close, but somewhere the lists aren't populating. Here is the code I'm using
//imports
import groovy.json.JsonSlurper
//grab the response
def ResponseMessage = messageExchange.response.responseContent
//define a JsonSlurper
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
//verify the slurper isn't empty
assert !(jsonSlurper.isEmpty())
def jsonlist =[]
def i = 0
while (jsonSlurper.BurgerJoints[i] != null)
{
if(jsonSlurper.BurgerJoints[i].JointName.toString().substring(0,3)=="Bob")
{
jsonlist.add(jsonSlurper.BurgerJoints[i])
}
i++
}
def jsonlist2 = new JsonSlurper().parseText(jsonlist.toListString())
assert jsonlist2.size()==3
Still not working unfortunately.
答案 0 :(得分:3)
以下是Groovy脚本,它声明JointName
包含值Bob's
的列表,值为3.请查找内联注释。
import groovy.json.JsonSlurper
//Defining json string a fixed value. Of course, you can use dynamic value
//using messageExchange like you shown in your question.
def jsonString = '''
{
"BurgerJoints": [
{
"JointName": "Bob's Burgers",
"Price": 5
},
{
"JointName": "Bob's Broiler Stand",
"Price": 5
},
{
"JointName": "Burger King",
"Price": 5
},
{
"JointName": "Bob's Beef Haven",
"Price": 5
},
{
"JointName": "Super Weenie Hut",
"Price": 5
}
]
}
'''
//Parse the string, create slurper object
def json = new JsonSlurper().parseText(jsonString)
//find all JointNames which contains Bob's, and apply size, and assert with 3
assert json.BurgerJoints.findAll { it.JointName.contains('Bob\'s')}.size() == 3
更新:根据评论,添加其他语句,以帮助实现此问题的作者所寻找的内容。
def jointList = json.BurgerJoints.findAll { it.JointName.contains('Bob\'s')}
log.info jointList
更新2 :根据其他评论,验证第1和第2的价格是否等于jointList
assert jointList[0].Price == jointList[1].Price