【发布时间】:2020-07-04 22:22:36
【问题描述】:
我有一个带有废话的大文本文件和一个 json 对象。我知道 json 对象有一个 textfile-far 唯一关键字,所以我会寻找这个唯一关键字。我知道这个词每次都在对象中,每次都在“根”位置下。这是一个示例 json-string
....
{
"key0":"value0",
"key1":"value0",
"key2":"value0",
"uniqueKey":"value0",
"key0":[
{"key0":"value0","key1":"value1"}
]
}
....
所以我写了这个方法来提取 json 对象: 它有效,但我认为 - 正则表达式?
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();
}
我问了我一个问题:可以正则表达式吗?一个星期六晚上之后,我不这么认为。我无法弄清楚如何制定“给我第一个尚未关闭的喷气式飞机的开放式支架”或“给我第一个尚未打开的喷气式飞机的封闭式支架”。有人可以帮帮我吗?
【问题讨论】:
-
只有在您知道要寻找的有限 JSON 结构的情况下,才有可能创建这样的正则表达式。您无法搜索无限的嵌套对象/数组。
-
所以孔对象每次都必须是相同的关键字?
-
不,关键字可能不同