1

我正在使用Json Path库来解析 JSON。我关注的是带有空格键的json:

{
    "attributes": {
        "First Name": "Jim",
        "Last Name": "Rohn"
    }
}

为了获得 的值First Name,我编写了如下代码(其中json包含 json 的对象在哪里) -

String firstName = JsonPath.from(json).getString("attributes.First Name");

但这会导致以下错误-

java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found 'Attributes' @ line 1, column 67.
   .First Name

您能否建议如何使用json-path库获取具有空格的键的值?

4

3 回答 3

3

尝试使用括号表示法First Name如下:

String firstName = JsonPath.from(json).getString("attributes.['First Name']");

更新

很抱歉混合JsoPath了不同的库。

如果您正在使用com.jayway.jsonpath,请尝试以下方式进行转义:

DocumentContext jsonContext = JsonPath.parse(json);
String firstName = jsonContext.read("$.attributes.['First Name']");

但如果你正在使用***.restassured.json-path,请使用这个:

String firstName = JsonPath.from(json).getString("attributes.'First Name'");
于 2020-01-21T09:13:07.967 回答
1

您必须用单引号转义密钥

使用以下代码:

String firstName = JsonPath.from(json).getString("'attributes.First Name'");
于 2020-01-21T09:08:07.200 回答
0

如果您使用io.restassured.path.json.JsonPath库,则路径表达式中需要转义序列。

String firstName = JsonPath.from(json).getString("attributes.\"First Name\"");

\" <-- Insert a double quote character in the text at this point.

所以你的路径表达式看起来像(attributes."First Name")并且可以被 JsonPath 库解析

于 2021-06-25T14:56:41.143 回答