6

I have JSON structure that is a nested parent/child kind of structure:

{
  "type": "site",
  "profile_id": "site profile id",
  "children": [
    {
      "type": "dealer",
      "profile_id": "dealer profile id",
      "children": [
        {
          "type": "location",
          "profile_id": "location profile id",
          "children": [
            {
              "type": "customer",
              "profile_id": "customer profile id",
              "children": [
                {
                  "type": "farm",
                  "farm_id": "farm id",
                  "children": [
                    {
                      "type": "field",
                      "field_id": "field id"
                     }]}]}]}]}]}

Is there some way in JSONPath to do one of the following:

  1. give me the profile_id if it's present, or give me the farm_id if it's present, or give me the field_id if it's present.

  2. give me the profile_id if type=customer, or give me the farm_id, if type=farm, or give me the field_id if type=field

  3. give me the nth attribute from each class. The id is actually the third attribute in each class. This is my least favorite option, because I don't know if the id will always be the third attribute.

Kurt Andrews
  • 79
  • 1
  • 7
  • If you are willing to do three JSONPath calls, option 2 would be pretty easy. Getting the profile_id if type=customer for example would look like this: `$..[?(@.type=='customer')].profile_id`. See [link](http://stackoverflow.com/questions/30680515/find-object-in-nested-data-by-property-value-with-jsonpath/30683008#30683008) for another example. Also, since you may run into issues with this, you are missing some syntax in your JSON, e.g. commas between fields, and double quotes around property names. – Duncan Jun 16 '15 at 21:57
  • Duncan, this worked fine for my situation. Also thanks for calling out the syntax. I'll edit the question to improve it. – Kurt Andrews Jun 26 '15 at 14:32
  • Glad I could help. I'll submit this as an official answer then so that the question can be closed. – Duncan Jun 27 '15 at 11:05

1 Answers1

6

A solution for option 2 that requires 3 separate queries would be the following. Here are the 3 queries:

$..[?(@.type=='customer')].profile_id
$..[?(@.type=='farm')].farm_id
$..[?(@.type=='field')].field_id

I verified these queries with http://www.jsonquerytool.com

Also see this question for a similar example.

Community
  • 1
  • 1
Duncan
  • 781
  • 6
  • 7