简体   繁体   中英

Unable to get value of key with spaces using JsonPath library

I'm using Json Path library to parse JSON. I've following json which has key with space:

{
    "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) -

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?

Try using bracket notation for First Name as follows:

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

UPDATE

Sorry for mixing different JsoPath libraries up.

If you are using com.jayway.jsonpath , try following way for escaping:

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

But if you are using ***.restassured.json-path , please use this one:

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.

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

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