1

I'm trying to build an HTTP request to a service which accepts a list of items, for example:

{
    "user": "john", 
    "table": "goods",
    "articles": [ 
        {"id": "003", "quantity": 1},
        {"id": "004", "quantity": 1},
        {"id": "023", "quantity": 2},
        {"id": "011", "quantity": 3},
        {"id": "063", "quantity": 1},
        {"id": "006", "quantity": 7}
    ]
}

My goal is to load ALL the articles from a CSV file, done as follows:

enter image description here

I would like to have something like:

{
    "user": "john", 
    "table": "goods",
    "articles": [ 
        {"id": "${id}", "quantity": ${qte}}
    ]
}

Can anyone help me?



UPDATE:

Dmitri T solved my problem, thank you! I also asked him how to add a JSON object (a dictionary) to my body, while he answer I found a solution which I will share here in case someone needs it. If you want to add:

"user": {"id": 1, "name": "John"}

to your body content, you just need to do this:

def user = [:]

//populate user
user.put('id', 1)
user.put('name', 'John')

//add user entity to body content
content.put("user", user)

Have fun!

1 Answer 1

3

You won't be able to have something like you provided above, the only way to dynamically build a JSON request body is constructing it programmatically using JSR223 PreProcessor

  1. Add JSR223 PreProcessor as a child of the request which body you want to parameterize
  2. Put the following code into "Script" area:

    def content = [:]
    content.put('user', 'john')
    content.put('table', 'goods')
    def articles = []
    new File('test.csv').readLines().each { line ->
        def article = [:]
        article.put('id', line.split(',')[0])
        article.put('quantity', line.split(',')[1])
        articles.add(article)
    }
    content.put('articles', articles)
    sampler.addNonEncodedArgument('', new groovy.json.JsonBuilder(content).toPrettyString(), '')
    sampler.setPostBodyRaw(true)
    
  3. That's it, when you run your test the PreProcessor will generate the request body from the CSV file and add it to the HTTP Request sampler on the fly.

References:

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Dmitri T, thank you for your answer. I think it is exactly what I'm searching for. Could you also telling me how to add directly a JSON entity to the script? Instead that: "user": "john" I would add: "user": {"id": 1, "name": "John"}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.