0

我有以下从外部来源获取的 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 命令或代码来实现吗?

4

2 回答 2

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 希望更新 step4 的现有请求以获取密钥及其值作为 step2 的响应。

使用示例来演示更改输入和所需输出。

让我们说,step2 的响应是:

{ 
    "world": "test1"
}

而 step4 的现有请求是:

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

现在,OP 想要在 ste4 的请求key中使用第一个响应来更新 的值,并且期望的是:

{
    "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)
于 2018-01-03T05:35:27.610 回答
0

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

 def validJSONString = JsonOutput.toJson(invalidJSONString).toString()
于 2018-01-03T09:54:30.077 回答