How can we save values (extracted from the JSON response) in a csv file?

For every API call, I need to save the value in a csv file to use it as a feeder in a different simulation.

How can we do this? Do we already have any solutions for this?

I had to do the same recently using this code. Hope you find use for it

implicit class StructureWithCustomSaveExtension(structure: ChainBuilder) {
def saveVariableToFile: ChainBuilder = {
structure.exec(session => {
Files.write(Paths.get(“filename to your csv file”), (session(“Some key to your saved value from json”).as[String] + “\n”).getBytes() , StandardOpenOption.APPEND);
session
})
}
}

You can then use it as this

.exec(Some request where you save the json results to an variable)
.saveVariableToFile

you can try following:

`
val writer = {
val fos = new java.io.FileOutputStream(“foo.csv”)
new java.io.PrintWriter(fos,true)
}
val scn = scenario(“FK”)
.exec(http(“LOGIN”)
.get("/gatling/2JEnbyNYiGg")
.check(jsonPath("$…lList…id").findAll.saveAs(“moreRows”))
)

.foreach("${moreRows}", “id”) {
exec(session => {
writer.println(session(“id”).as[String])
session})
}
`

HI Team,
This is not working, getting error like java.io.FileNotFoundException: data/numbersIDs.csv (No such file or directory)

below is the code which i tried to execute, datd driven testing is working fine but now able to write data to csv.

class fetch_user_info extends BaseSimulation {

//define feeder
val csvfeeder = csv(fileName = “data/UserLoginwithEmail.csv”)

//Define Request
def User_login_with_emial_method(): ChainBuilder = {
feed(csvfeeder)
.exec(http(requestName = “User Login with Email”)
.post(url = “/dealer/user/v1/login”)
.body(StringBody(
“”"

{“emailId”: “${emailId}” ,“password”: “${password}”}

“”“.stripMargin)).asJson
.check(jsonPath(path = “$.data.auth.token”).saveAs(key = “numberIDs”))
.check(bodyString.saveAs(“RESPONSE_DATA”)))
.exec(session => {
println(“Some Restful Service Response Body:”)
println(session(“RESPONSE_DATA”).as[String])
session
})
//Save variable numberIDs into the csv file
.foreach(”${numberIDs}", “id”) {
exec(session => {
numberIDs_writer.println(session(“id”).as[String])
session
})
}

}

//Variables to store the extracted values of the response
var numberIDs : Seq[String] = _

//Java Writer
val numberIDs_writer = {
val fos = new java.io.FileOutputStream(“data/numbersIDs.csv”)
new java.io.PrintWriter(fos,true)
}

//setup scenario

val scn = scenario(scenarioName = “Trying to generate OTP for Mobile registered Users”)
.exec(User_login_with_emial_method())

//inject User -Load profile
setUp(scn.inject(atOnceUsers(users = 1))
//rampusers(500) over (30 minutes).maxDuration(3600 seconds)
.protocols(httpConf))
}

This is not a question relative to gatling. See java file management

My guess: the “data” directory does not exist.

Generally, the feeder get its data from a resource (a file in the generated jar)
So I guess your “data/UserLoginwithEmail.csv” file is in src/test/resources

But new java.io.FileOutputStream(“data/numbersIDs.csv”) will try to open (in write mode) the file relative to the current working directory.
Depending on your current working directory, the data may not exists and the JVM cannot create a numbersIDs.csv in a directory that does not exist.

For more information, please google about Java file management.

Dear Sébastien BREVET,

Please can you guide me with how to store json response in common class so that i can use in next class.

My scenario : From login API token ID will be generated , this token need to use in separate classes how can i achieve scenario.

My try with code

//Define Request
def User_login_with_emial_method(): ChainBuilder = {
feed(csvfeeder)
.exec(http(requestName = “User Login with Email”)
.post(url = “/dealer/user/v1/login”)
.body(StringBody(
“”"

{“emailId”: “${emailId}” ,“password”: “${password}”}

“”".stripMargin)).asJson
.check(jsonPath(path = “$.data.auth.token”).saveAs(key = “token”)))
.exec(session => {
println(“this is token”)
println(session(“token”).as[String]);
session
})

Hi Guys,

Im able to find solution for saving json response into CSV file. Hopefully this will help you .

import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
import io.gatling.core.structure.ChainBuilder
import java.io.File
import java.io.PrintWriter
import java.io.FileOutputStream

class fetch_user_info extends BaseSimulation {

//define feeder
val csvfeeder = csv(fileName = “data/UserLoginwithEmail.csv”) // To read Login Credentials from this file

//Define Request
def User_login_with_emial_method(): ChainBuilder = {
feed(csvfeeder)
.exec(http(requestName = “User Login with Email”)
.post(url = “/dealer/user/v1/login”)
.body(StringBody(
“”"

{“emailId”: “${emailId}” ,“password”: “${password}”}

“”“.stripMargin)).asJson
.check(jsonPath(path = “$.data.auth.token”).saveAs(key = “token”)))
.exec { session =>
println(“this is token”)
println(session(“token”).as[String])
val writer = new PrintWriter(new FileOutputStream(new File(“src/test/resources/data/EmailLoginToken.csv”), false))
writer.write(session(“token”).as[String])
writer.write(”\n")
writer.close()
session }
}

//setup scenario

val scn = scenario(scenarioName = “Trying to generate OTP for Mobile registered Users”)
.exec(User_login_with_emial_method())

//inject User -Load profile
setUp(scn.inject(atOnceUsers(users = 1))
//rampusers(500) over (30 minutes).maxDuration(3600 seconds)
.protocols(httpConf))
}

I had a similar requirement to read the response values and log it to the logfile (csv ).

  1. used the file appender
    In pom.xml add this dependency
com.typesafe.scala-logging scala-logging_2.13 3.9.2