tomi
tomi

Reputation: 423

Is there a way to get back both path and value from JsonPath?

I am trying to get both path and value from the following JSON object using JsonPath:

[
  {
    "id": 1,
    "person": {
      "name": "john",
      "age": "28"
    }
  },
  {
    "id": 2,
    "person": {
      "name": "jane",
      "age": "25"
    }
  }
]

When using path: "$[*].person.name" I'm getting back ["john", "jane"]. I would like to get back something like:

    [{"john", "$[0].person.name"},
     {"jane", "$[1].person.name"}]

I need the value and the exact path where it is found.

Upvotes: 1

Views: 1271

Answers (1)

glytching
glytching

Reputation: 47865

You can read the paths and the values separately and then put the results together.

Here's an example using Jayway JsonPath:

String json = "[\n" +
        "  {\n" +
        "    \"id\": 1,\n" +
        "    \"person\": {\n" +
        "      \"name\": \"john\",\n" +
        "      \"age\": \"28\"\n" +
        "    }\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 2,\n" +
        "    \"person\": {\n" +
        "      \"name\": \"jane\",\n" +
        "      \"age\": \"25\"\n" +
        "    }\n" +
        "  }\n" +
        "]";

Object parse = Configuration.defaultConfiguration()
        .jsonProvider()
        .parse(json);

JsonPath path = JsonPath.compile("$[*].person.name");

// read the paths
JSONArray asPaths = path.read(parse, Configuration.builder()
        .options(Option.AS_PATH_LIST).build());
String[] paths = asPaths.toArray(new String[asPaths.size()]);

// read the values
JSONArray asValues = path.read(parse);
String[] values = asValues.toArray(new String[asValues.size()]);

// put the paths and values together using the array indexes
Map<String, String> valuesAndPaths = new HashMap<>();
for (int i = 0; i < values.length; i++) {
    valuesAndPaths.put(values[i], paths[i]);
}

for (Map.Entry<String, String> entry : valuesAndPaths.entrySet()) {
    System.out.println(entry.getKey() + ", " + entry.getValue());
}

This will print out:

john, $[0]['person']['name']
jane, $[1]['person']['name']

Upvotes: 2

Related Questions