1

I have json

[
  {
    "name": "Name1",
    "address": "City1\nCountry1"
  },
  {
    "name": "Name2",
    "address": "City2 Country2"
  }
]

And I am using jayway library to extract "name" using "address". I want to parameterize the "address" using jpath

$.*[?(@.address=='{address}')].name

However, as you can see in json, first address has "\n" on it. Is there a way like normalize spacing for it so whenever I use jpath

$.*[?(@.address=='City1 Country1')].name

the value will still be extracted

Smile
  • 3,832
  • 3
  • 25
  • 39
  • I'm not sure how you are reading may be from file or API. convert JSON to string if not already a string then replace all \n's with space " ". If you can post a sample code of what you have tried then we can suggest few approaches – Krk Rama Krishna Sep 16 '20 at 06:36
  • Thanks for your comment. That's the workaround I am doing right now, from API response -> convert to string -> response.replace("\\n"," "). However, I am curious if we have solution like with selenium xpath locator which uses "normalize-space()" – Millie Anne Volante Sep 16 '20 at 07:17
  • I hope the answer provided some insights. – wp78de Jan 21 '21 at 18:00

1 Answers1

0

A little late, a possible JSON-Path soltution is to use the contains operator for both parts:

$..[?(@.address contains 'City1' && @.address contains 'Country1')].name

However, this is not the same as a == comparison and could theoretically produce false positives.

Another option is to use the regex filter =~. Using it gives you full control and the ability to only match what you want; since you have a newline we need to inline (?s) to make .* match any character including newlines.

$..[?(@.address =~ /(?s)City1.*Country1/i)].name
wp78de
  • 18,207
  • 7
  • 43
  • 71