Usability - Productivity - Business - The web - Singapore & Twins

Query a JSON object like XPath in Java

I'm fond of XML especially XSLT and the related XPath query possibilities.
Moving into the wonderworld of JSON I'm missing those platform independent query and rendering options.
For templating Mustache comes close, especially in regards of platform support, but XPath still has to find its match in the JSON world.

The closest equivalent is JSONPath (also available for Java ) with a nice interactive playground.

I was looking at adopting it for one of my projects written in vert.x.
JSON isn't native to Java and there are several competing implementations around JSON: Google's GSON, Jackson
and vert.x core JsonObject (there are probably more).

So I was wondering: What if I could use XPath and by extension XSLT directly on JSON? The first step there would be a save way to transform JSON to XML and back.
Using vert.x JsonObject and JsonArray as starting point,
I had the following considerations:

  • I can't use XML tags to map to JSON labels, since labels can contain any character, XML tags are restricted
  • The resulting XML only needs 2 elements: Element and Array
  • An element can have a scalar value, my first test deals with strings only, or can contain another element or array
  • An array does not have a value. It can contain zero or more scalar values and/or zero or more arrays or elements

So I build a small prototype. A simple class that reads a json file from the command line, prints it to the console, transforms it to XML, prints it to the console, transforms it back and prints it again.
The prototype depends on vert.x core.

The result can be found in this gist or read more.

Give it a spin and let me know how it works for you. It's just the beginning.
Next stop: apply XPath operations on the resulting XML before transforming it back.

As usual: YMMV

Posted by on 28 February 2018 | Comments (0) | categories: Java vert.x


  1. No comments yet, be the first to comment