0

I want to know the name who purchased items "abc" and "def" from the bellow json data. (Expected result is "tom")

Please tell me how to do using JsonPath.

[
  {
    "name": "tom",
    "purchased": [
      {
        "name": "abc"
      },
      {
        "name": "def"
      }
    ]
  },
  {
    "name": "bob",
    "purchased": [
      {
        "name": "xyz"
      }
    ]
  }
]
  • Could you add what you've tried, please? This community generally likes to see some level of effort rather than "solve my problem for me" type questions. – gregsdennis Dec 01 '20 at 03:03
  • Hi. Which JSONPath implementation you are using, where are you using this? – wp78de Dec 07 '20 at 18:24

1 Answers1

0

If you are doing this in Java you could select the name of the buyer like this:

$..[?(@.purchased && @..name contains 'abc' && @..name contains 'def' )].name

In JavaScript, you can use this a query like this:

$.[?(@.purchased && @.purchased.some(e => e.name==='abc') && @.purchased.some(e => e.name==='def') )].name

Both queries use a similar approach:

  • We filter for a purchased-property, then use a function to search the keys in the map for certain values
    • Jayway's JsonPath offers a contains function to do so;
    • In JavaScript we leverage script evaluation to search the map/dict for our key/values
      So, the .some() is not a JsonPath function but some modern JavaScript (:D).
  • This is kind of a workaround in both cases but it gets the job done.

You can test both online here. Select the tab JayWay and click Go for the first query, switch to tab Goessner to run the JavaScript sample (you can run the second here as well).

wp78de
  • 18,207
  • 7
  • 43
  • 71