Search code examples
javajsonpathjsonparser

Json path get all first attributes


I have below json, I am trying to fetch 1st attributes from each nodes, using jsonPath.

 {   "data": {
        "unpredictable_name_1": {
          "inner_data": [
            {
              "wanted_data": "something1",
              "other_data": 1000
            },
            {
              "wanted_data": "something2",
              "other_data": 1001
            }
          ],
          "something_else_1": "some_data"
        },
        "unpredictable_name_2": {
          "inner_data": [
            {
              "wanted_data": "something1",
              "other_data": 1000
            },
            {
              "wanted_data": "something2",
              "other_data": 1001
            }
          ]
        }   } }

I want to extract below :

{
    unpredictable_name_1, 
    unpredictable_name_2
}

I am using jway-json path. Please help me with the jsonPath expression.


Solution

  • This code helped me get all the json attributes only -

    JsonParser parser = new JsonParser();
          JsonElement element = parser.parse(jsonStr);
          JsonObject obj = element.getAsJsonObject();
          Set<Map.Entry<String, JsonElement>> entries = obj.entrySet();
          for(Map.Entry<String, JsonElement> entry: entries) {
             System.out.println(entry.getKey());
          }
    

    Thanks to Tutorials Point