How do I retrieve a value from a JSON string using gatling JsonPath.query?

2.1k views Asked by At

Given a string:

val json = """{"id":"derp"}"""

When I try to retrieve the value of ID using JsonPath I get the empty iterator

import io.gatling.jsonpath.JsonPath

JsonPath.query("$.id", json).right.get
// Iterator[Any] = empty iterator

How do I get the value of id?

1

There are 1 answers

2
Antot On BEST ANSWER

Although the type of the second arg to JsonPath.query is Any, this function does not seem to support multiple types of arguments. It does not parse the input string, but expects it already to be parsed. Looks a bit weird as design choice.

So, supposing that Jackson is used as the parser lib, the following will work and select the value under id key:

val json = """{"id":"derp"}"""
val parsed = new ObjectMapper().readValue(json, classOf[Object])

// to retrieve the ids as a list:
val ids = JsonPath.query("$.id", parsed).right.get.toList

// the only "id" result of the query
val id = ids.head