Skip to content
Advertisement

Get the line number of a JSON file given a JSON Path/JSON Pointer in Java

I am looking for a way to parse a JSON file for a specific node and get that node’s line number in the file. I would like to use the Jayway JSONPath library to support extended JSONPath queries.

For example (from jsonpath.com), here’s some JSON:

JavaScript

and here’s a jsonPath: $.phoneNumbers.[?(@.type=='iPhone')]

I would like to have a way to say that this node is on line 11 in the json file. I don’t know ahead of time what the json contents might be or the jsonPath. Both are dynamic.

So far, I’ve tried to parse the json into a tree and traverse it up to the node to get the parser’s current location, but the parser must always run to the end of the file before the jsonPath executes. Any other ideas?

Advertisement

Answer

I eventually found a solution that involves using Jackson’s JsonFactory and JsonParser. It’s kludge-y to say the least, but it uses the JsonParser’s knowledge of its parser’s line number to get the JsonNode’s position and works pretty well.

I’ll paste the code here, but the code is also available at watchtower github

Calling class:

JavaScript

CustomJsonNodeFactory.java

JavaScript

CustomParserFactory.java (Note that this removes thread-safety, which can be kind of a big deal):

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement