0

I have some JSON data which contains an element that is an array; however, when the array only contains one element, then the information is provided as a string instead of as an array. See the $.phoneNumbers.type element below. In the first phone number, the "type" element is represented as an array, but the array only contains one element ("iPhone"). In the second phone number, the type is just a simple string ("home").

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "phoneNumbers": [
    {
      "type"  : ["iPhone"],
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
}

When I attempt to parse this with JSONPath using this expression:

$.phoneNumbers[0].type[0]

I get the following error when the element is not wrapped in array brackets.

Filter: [0] can only be applied to arrays. Current context is: home - Line: 0"

Is there a JSONPath expression which can successfully parse either of these? Basically, I think I need something that will check to see if the element is an array or a string first, and then adjust as needed like this:

If it is an array: $.phoneNumbers[0].type[0]

If it is a string: $.phoneNumbers[0].type

Is this possible?

1 Answer 1

1

When using your JSON input with https://jsonpath.curiousconcept.com i can use the following JSONPath query to get both the "iPhone" and "home" values: $.phoneNumbers[*].type

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.