[英]Unable to get value of key with spaces using JsonPath library
I'm using Json Path library to parse JSON.我正在使用Json Path库来解析 JSON。 I've following json which has key with space:
我正在关注具有空格键的 json:
{
"attributes": {
"First Name": "Jim",
"Last Name": "Rohn"
}
}
In order to get value of First Name
, I wrote code like (where json
is object which holds above json) -为了获得
First Name
的价值,我编写了类似的代码(其中json
是包含在 json 之上的对象)-
String firstName = JsonPath.from(json).getString("attributes.First Name");
But it results into following error -但它会导致以下错误 -
java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found 'Attributes' @ line 1, column 67.
.First Name
Could you please suggest how to get values of key having spaces using json-path
library?您能否建议如何使用
json-path
库获取具有空格的键的值?
Try using bracket notation for First Name
as follows:尝试对
First Name
使用括号表示法,如下所示:
String firstName = JsonPath.from(json).getString("attributes.['First Name']");
UPDATE更新
Sorry for mixing different JsoPath
libraries up.很抱歉混淆了不同的
JsoPath
库。
If you are using com.jayway.jsonpath
, try following way for escaping:如果您使用的是
com.jayway.jsonpath
,请尝试以下方式进行转义:
DocumentContext jsonContext = JsonPath.parse(json);
String firstName = jsonContext.read("$.attributes.['First Name']");
But if you are using ***.restassured.json-path
, please use this one:但是如果你使用的是
***.restassured.json-path
,请使用这个:
String firstName = JsonPath.from(json).getString("attributes.'First Name'");
You have to escape the key with single quotes你必须用单引号转义钥匙
Use below code:使用以下代码:
String firstName = JsonPath.from(json).getString("'attributes.First Name'");
If you are using io.restassured.path.json.JsonPath library then Escape Sequences is required in the path expression.如果您使用的是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.
So your path expression looks like (attributes."First Name")
and can be parsed by JsonPath library所以你的路径表达式看起来像
(attributes."First Name")
并且可以被 JsonPath 库解析
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.