简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM