Need to update value in .json file and call API

I need to update timestamp value from Json file. And call API. But timestamp value is not updated when API is called.

    val records = jsonFile("json-files/requests.json").records
    val date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
    /**
     * Triggers
     */
    val triggerForPostRequests = feed(records.circular).exec(session => {
        session("payload").session.set("timestamp", date.format(System.currentTimeMillis()))
        session
    }).exec(http("simulation").
        post(session => session("uri").as[String].replace("{uuid}", randomUUID().toString))
       .body(StringBody("${payload.jsonStringify()}".replace("${timestamp}", date.format(System.currentTimeMillis())))).check(status.is(200)))

Request JSON inside file.

[
  {
    "method": "post",
    "uri": "/v2/{uuid}?comment=abc",
    "payload": [
      {
        "timestamp": "${timestamp}",
        "timezoneOffset": 420
      }
    ]
  }

]

Result of above.

compositeByteData=[{"timestamp":"${timestamp}","timezoneOffset":420}]

Hi @imtiaz_ali!

Welcome aboard!

Your issue lie in the order of actions that are made.

In your code:

StringBody("${payload.jsonStringify()}".replace("${timestamp}", date.format(System.currentTimeMillis())))

is the same thing as:

val payload: String = "${payload.jsonStringify()}".replace("${timestamp}", date.format(System.currentTimeMillis()))
StringBody(payload)

The the replace method really apply on the given String, not the content of your session value.

So it’s equivalent to:

val payload: String = "${payload.jsonStringify()}"
StringBody(payload)

It’s the reason why you don’t see the replacement into the final value.

You should replace as you did in the post argument

  val triggerForPostRequests =
    feed(records.circular)
      .exec(http("simulation")
        .post(session => session("uri").as[String].replace("{uuid}", randomUUID().toString))
        .body(StringBody{ session =>
          session("payload").as[JsonNode]
            .toString
            .replace("${timestamp}", date.format(System.currentTimeMillis()))
        })
        .check(status.is(200)))

Note: I removed the first exec, because you return the initial session (instead of returning the updated one)

Hope that helps.
Cheers!

Hello @sbrevet thanks for your response.

.body(StringBody{ session =>
          session("payload").as[JsonNode]
            .toString
            .replace("${timestamp}", date.format(System.currentTimeMillis()))
        })

The above code you suggested, it returns

[{timestamp=2023-02-23T14:32:31, timezoneOffset=420}] .

But, the required output is

[{"timestamp":"2023-02-23T14:32:31","timezoneOffset":420}] ,

which is like Json.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.