1

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?

Alpha
  • 13,320
  • 27
  • 96
  • 163

3 Answers3

5

Try using bracket notation for First Name as follows:

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

UPDATE

Sorry for mixing different JsonPath 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'");
LHCHIN
  • 3,679
  • 2
  • 16
  • 34
  • I've used `io.rest-assured.rest-assured.4.1.2` which internally uses `io.rest-assured.json-path.4.1.2` – Alpha Jan 22 '20 at 06:19
  • 1
    @TDHM So does the solution in this post [How do I get the value of a key if it contains a space in Rest Assured / Serenity?](https://stackoverflow.com/q/45112425/6469772) also not help? – LHCHIN Jan 22 '20 at 06:31
  • Thanks a lot man it helped! It should be like `attributes.'First Name'` – Alpha Jan 22 '20 at 06:41
  • @TDHM Great! I have updated my post, please check it out! – LHCHIN Jan 22 '20 at 07:15
  • Thanks I was stuck in this but not it works. return_reason_(l1) this key was the issue $.order_details[0].return_items[0].return_reasons[0]['return_reason_(l1)'].code – Bhushan Nov 23 '22 at 12:37
1

You have to escape the key with single quotes

Use below code:

String firstName = JsonPath.from(json).getString("'attributes.First Name'");
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
  • This does not give any error but returns `null` as a value even though there is non-null value. – Alpha Jan 22 '20 at 05:02
0

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