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:
{
"firstName": "John",
"lastName" : "doe",
"age" : 26,
"address" : {
"streetAddress": "naist street",
"city" : "Nara",
"postalCode" : "630-0192"
},
"phoneNumbers": [
{
"type" : "iPhone",
"number": "0123-4567-8888"
},
{
"type" : "home",
"number": "0123-4567-8910"
}
]
}
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?
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:
CustomJsonNodeFactory.java
CustomParserFactory.java (Note that this removes thread-safety, which can be kind of a big deal):