简体   繁体   English

如何使用加特林JsonPath.query从JSON字符串中检索值?

[英]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 当我尝试使用JsonPath检索ID的值时,我得到了空的迭代器

import io.gatling.jsonpath.JsonPath

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

How do I get the value of id? 如何获得id的值?

Although the type of the second arg to JsonPath.query is Any , this function does not seem to support multiple types of arguments. 尽管JsonPath.query的第二个arg的类型是Any ,但此函数似乎不支持多种类型的参数。 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: 因此,假设将Jackson用作解析器库,则将执行以下操作并选择id键下的值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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