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"
      }
    ]
  }
]
2
  • 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. Commented Dec 1, 2020 at 3:03
  • Hi. Which JSONPath implementation you are using, where are you using this? Commented Dec 7, 2020 at 18:24

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.