0

I have a JSON that structured as below. I am using JSONPath Expression to filter values only. How does one filter and output only those values where the first three characters of those values match with a given three characters.

[
  {
    "firstName": "John",
    "lastName": "doe",
    "age": 26,
    "address": {
      "streetAddress": "naist street",
      "city": "Nara",
      "postalCode": "630-0192"
    },
    "phoneNumbers": [
      {
        "model": "iPhone",
        "number": "0123-4567-8888"
      },
      {
        "model": "iPhoneX",
        "number": "0123-4567-8910"
      }
    ]
  },
  {
    "firstName": "Ram",
    "lastName": "Pavan",
    "age": 29,
    "address": {
      "streetAddress": "Delhi street",
      "city": "Noid",
      "postalCode": "222-211"
    },
    "phoneNumbers": [
      {
        "model": "iPhone 6S",
        "number": "43212-888-9998"
      },
      {
        "model": "iPhone 14",
        "number": "84848-337-83330"
      }
    ]
  }
]

In the above sample JSON, I was successful in filtering all values that has model as the key using this JSONPath expression:

$..model

The output was as expected a list of all models:

[
  "iPhone",
  "Samsung",
  "iPhone 6S",
  "iPhone 14"
]

That was fine, but then if I had to filter only those values that starts with (begins with) a given set of characters iph or iPhone then how does one write the expression. The desired output in this case should be as follows:

[
  "iPhone",
  "iPhone 6S",
  "iPhone 14"
]
Naveen Chand K
  • 411
  • 1
  • 5
  • 13

1 Answers1

0

After some trials, I tried to apply Javascript slice() method to the values. But before that I also had to go up by one level and then filter elements under that parent using the filter ? and slice combination.

Here is the code that worked for me:

$..phoneNumbers[?((@.model).slice(0,3) == "iPh")].model

Slice method has two parameters (start, end). In this case, the starting index is 0 and the ending index is 3 which should then equal "iPh".

The desired output:

[
  "iPhone",
  "iPhone 6S",
  "iPhone 14"
]
Naveen Chand K
  • 411
  • 1
  • 5
  • 13
  • 1
    you can also use Regular Expression `$..phoneNumbers[?(@.model.match(/^iPhone.*/))]` – Akshay G Feb 22 '23 at 13:51
  • excellent. your suggested expression works well. I tried to filter with first three characters and it was still working: `$..phoneNumbers[?(@.model.match(/^iPh.*/))]` – Naveen Chand K Feb 25 '23 at 16:01