Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you get the JSON Path?

Tags:

java

json

Given a sample JSON:

{
  "hello" : "wolrd",
  "arrayField" : ["one", "two", "three"],
  "mapField" : {
    "name" : "john",
    "lastName" : "doe" 
  }
}

Is there a framework in Java to help me get the JSON path structure from the JSON tree? Something similar to this:

$.hello
$.arrayField[0]
$.arrayField[1]
$.arrayField[2]
$.mapField.name
$.mapField.lastName

EDIT:

I've already coded a first approach using fasterxml's Jackson. But I'd like to know if there's something more robust / flexible.

   final JsonNode rootNode = mapper.readValue(jon, JsonNode.class);
    printFieldKeys(rootNode, "$");

    private static void printFieldKeys(JsonNode rootNode, String parent) {
        final Iterator<Entry<String, JsonNode>> fieldIt = rootNode.fields();
        while (fieldIt.hasNext()) {
            final Entry<String, JsonNode> next = fieldIt.next();
            final JsonNode value = next.getValue();
            final String path = parent + "." + next.getKey();

            if (value.isValueNode()) {
                System.out.println(path + " = " + value.asText());
            } else  {
                System.out.println(path);
            }


            if (value.isArray()) {
                for (int i = 0; i < value.size(); i++) {
                    printFieldKeys(value.get(i), path + "[" + i + "]");
                }
            } else {
                printFieldKeys(value, path);
            }

        }
    }
like image 353
Russell Avatar asked Nov 01 '22 00:11

Russell


1 Answers

Take a look at this library: https://github.com/jayway/JsonPath

I believe it does exactly what you want. :)

like image 115
Lucas Saldanha Avatar answered Nov 09 '22 10:11

Lucas Saldanha