Search code examples
javarest-assuredrest-assured-jsonpath

RestAssured JsonPath: Issue with getting data from json


I need to take a data from json file which has a weird structure and i can't find a solution for it. I'm using restAssured with jsonPath and when i'm trying to get data for particular week like this

getJsonPath().getList("years.2017.weeks.find{it.isoWeekNum == '1'}")

i'm getting an error

Invalid JSON expression: Script1.groovy: 1: unexpected token: 2017 @ line 1, column 33.
 years.2017.weeks.find{it.isoWeekNum == '1'}

At the same time i can get data with this expression

getJsonPath().getList("years.2017.weeks")

which returns to me the all list of weeks.

The only way that i found to get what i need is like this

getJsonPath().getList("years[1]['2017'].weeks.find{it.isoWeekNum == '1'}")

But this is not what i'm looking for. I need to find a solution where i can get data without years[1] for 2017 and years[0] for 2016

 "{
  "years": [
    {
      "2016": {
        "currentIsoWeek": "49",
        "currentTourWeek": "49",
        "weeks": [
          {
            "isoWeekNum": "1",
            "tourWeekNum": "1",
            "categories": []
          },
          {
            "isoWeekNum": "2",
            "tourWeekNum": "2",
            "categories": []
          }
        ]
      }
    },
    {
      "2017": {
        "currentIsoWeek": "",
        "currentTourWeek": "",
        "weeks": [
          {
            "isoWeekNum": "1",
            "tourWeekNum": "1",
            "categories": []
          },
          {
            "isoWeekNum": "2",
            "tourWeekNum": "2",
            "categories": []
          }
        ]
      }
    }
  ]
}

Solution

  • Hope the following code is exactly what are you looking for:

    public static void main(final String[] args) {
        JsonPath jsonPath = new JsonPath(yourJson).using(new JsonPathConfig("UTF-8"));
    
        System.out.println(
                jsonPath.get("years['2017'].weeks*.find {it.isoWeekNum == '1'}")
        );
    }