I have a large textfile with nonsense and a json object somewhere in it. I knew that the json object has a textfile-far unique keyword so I'll look for this unique keyword. I knew this word is every time in the object and every time under the "root" location. Here is an Example json-string
....
{
"key0":"value0",
"key1":"value0",
"key2":"value0",
"uniqueKey":"value0",
"key0":[
{"key0":"value0","key1":"value1"}
]
}
....
so I had wrote this method to extract the json object: It works find but I thought - regex?
private JsonObject parse(String text, String keywordInJsonFile) {
int index = text.indexOf(keywordInJsonFile);
int lastIndex = text.lastIndexOf(keywordInJsonFile);
if (index != lastIndex) {
log.warn("The keyword isn't unique please check your input file '{}'", keywordInJsonFile);
log.warn("Continue with the first match at index {}", index);
}
int indexJsonStart;
int indexJsonStop;
int currentIndex = index;
int bracketCounter = 0;
// loop and find the first '{' from the json Object
while (true) {
currentIndex--;
char c = text.charAt(currentIndex);
if (c == '}') bracketCounter++;
if (c == '{') bracketCounter--;
if (c == '{' && bracketCounter == -1)
{
indexJsonStart = currentIndex;
break;
}
}
currentIndex = index;
bracketCounter = 0;
// loop and find the last '}' from the json Object
while (true) {
currentIndex++;
char c = text.charAt(currentIndex);
if (c == '}') bracketCounter++;
if (c == '{') bracketCounter--;
if (c == '}' && bracketCounter == 1)
{
indexJsonStop = currentIndex +1;
break;
}
}
// Gson -> JsonObject has to be between the { }
return new JsonParser().parse(text.substring(indexJsonStart, indexJsonStop)).getAsJsonObject();
}
I asked me the question: is it possible to regex it? A Saturday evening later and I don't think so. I can't figure out how I can formulate the "give me the first open bracket that hasn't ben closed jet" or "give me the first close bracket that hasn't ben opened jet". can someone help me out?