可以使用groovy将JSON字符串格式转换为实际格式吗?

时间:2018-01-02 13:08:36

标签: json rest groovy soapui ready-api

我从外部源获取以下JSON字符串格式: - 这实际上是什么样的格式?

{
id=102,
brand=Disha,
book=[{
   slr=EFTR,
   description=Grammer,
   data=TYR,
   rate=true,
   numberOfPages=345,
   maxAllowed=12,
   currentPage=345
   },
   {
   slr=EFRE,
   description=English,
   data=TYR,
   rate=true,
   numberOfPages=345,
   maxAllowed=12,
   currentPage=345
  }]
}

我想将其转换为实际的JSON格式,如下所示: -

{
"id": "102",
"brand": "Disha",
"book": [{
    "slr": "EFTR",
    "description": "Grammer",
    "data": "TYR",
    "rate": true,
    "numberOfPages": 345,
    "maxAllowed": "12",
    "currentPage": 345
    },
    {
    "slr": "EFRE",
    "description": "English",
    "data": "TYR",
    "rate": true,
    "numberOfPages": 345,
    "maxAllowed": "12",
    "currentPage": 345
   }]
}

使用groovy命令或代码可以实现吗?

2 个答案:

答案 0 :(得分:1)

一些事情:

  • 您不需要Groovy Script测试步骤,该测试步骤当前为步骤3
  • 对于第2步,使用下面给出的脚本
  • 添加“脚本断言”
  • 在下面的脚本中为nextStepName提供您要添加请求的步骤名称。
//Provide the test step name where you want to add the request
def nextStepName = 'step4'

def setRequestToStep = { stepName, requestContent ->
    context.testCase.testSteps[stepName]?.httpRequest.requestContent = requestContent   
}

//Check the response
assert context.response, 'Response is empty or null'
setRequestToStep(nextStepName, context.response)

编辑:根据与OP在聊天中的讨论,OP希望更新步骤4的现有请求以获取密钥,并将其值更新为step2的响应。

使用样本来演示变更输入和所需输出。

让我们说,step2的回应是:

{ 
    "world": "test1"
}

step4的现有请求是:

{
    "key" : "value",
    "key2" : "value2"
}

现在,OP想要更新key的值,并在ste4的请求中以第一个响应 ,并且希望:

{
    "key": {
        "world": "test1"
    },
    "key2": "value2"
}

以下是更新的脚本,在Script Assertion中用于第2步:

//Change the key name if required; the step2 response is updated for this key of step4
def keyName = 'key'

//Change the name of test step to expected to be updated with new request
def nextStepName = 'step4'

//Check response
assert context.response, 'Response is null or empty'

def getJson = { str ->
    new groovy.json.JsonSlurper().parseText(str)
}

def getStringRequest = { json ->
    new groovy.json.JsonBuilder(json).toPrettyString()
}

def setRequestToStep = { stepName, requestContent, key ->
    def currentRequest = context.testCase.testSteps[stepName]?.httpRequest.requestContent
    log.info "Existing request of step ${stepName} is ${currentRequest}"
    def currentReqJson = getJson(currentRequest)
    currentReqJson."$key" = getJson(requestContent) 
    context.testCase.testSteps[stepName]?.httpRequest.requestContent = getStringRequest(currentReqJson)
    log.info "Updated request of step ${stepName} is ${getStringRequest(currentReqJson)}"   
}


setRequestToStep(nextStepName, context.request, keyName)

答案 1 :(得分:0)

我们可以使用以下代码行将无效的JSON格式转换为有效的JSON格式: -

 def validJSONString = JsonOutput.toJson(invalidJSONString).toString()