如何在JMeter的JSON请求中追加额外字段

huangapple go评论62阅读模式
英文:

How to append extra field in json request of jmeter

问题

{
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON:API paints my bikeshed!",
      "body": "The shortest article. Ever."
    },
    "relationships": {
      "author": {
        "data": {"id": "42", "type": "people"}
      }
    }
  }],
  "included": [{
    "type": "people",
    "id": "42",
    "attributes": {
      "name": "John",
      "Gender": "Male"
    }
  }]
}
英文:

we have 10K payload requests in file, we need to hit each json file from jmeter but before passing the request few fields need to be appended.

For example
Before format

    {
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON:API paints my bikeshed!",
      "body": "The shortest article. Ever."
    },
    "relationships": {
      "author": {
        "data": {"id": "42", "type": "people"}
      }
    }
  }],
  "included": [
    {
      "type": "people",
      "id": "42",
      "attributes": {
        "name": "John"
      }
    }
  ]
}

How to append below highlighted attribute

After format

{
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON:API paints my bikeshed!",
      "body": "The shortest article. Ever."
    },
    "relationships": {
      "author": {
        "data": {"id": "42", "type": "people"}
      }
    }
  }],
  "included": [
    {
      "type": "people",
      "id": "42",
      "attributes": {
        "name": "John",
        **"Gender": "Male"**
      }
    }
  ]
}

答案1

得分: 0

  1. JSR223 PreProcessor添加为HTTP请求采样器的子元素,您希望修改其负载的采样器。
  2. 将以下代码放入“脚本”区域:
def payload = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
payload.included[0].attributes.put('Gender','Male')
sampler.getArguments().getArgument(0).setValue(new groovy.json.JsonBuilder(payload).toPrettyString())
  1. 就这样,预处理器将在运行时修改请求体。

更多信息:

英文:
  1. Add JSR223 PreProcessor as a child of the HTTP Request sampler which payload you want to modify

  2. Put the following code into the "Script" area:

    def payload = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
    payload.included[0].attributes.put('Gender','Male')
    sampler.getArguments().getArgument(0).setValue(new groovy.json.JsonBuilder(payload).toPrettyString())
    
  3. That's it, the PreProcessor will amend the request body in the runtime

More information:

huangapple
  • 本文由 发表于 2023年4月10日 19:42:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定