我有一堆自定义脚本,其文件格式类似,但与JSON不同。我想获取这些文件并将其数据吐入QTreeWidget并显示原始代码并使用一些语法高亮显示。我不需要完成这些任务,我只需要一个干净的方法或想法如何从这些中提取信息。以下是脚本中的示例代码段。
示例:
"People"
{
"Person 1"
{
"age" "34"
"name" "John"
"gender" "male"
"skills"
{
"skill 1" "Intelligent"
"skill 2" "Wise"
"skill 3" "Buff as a bear!"
}
}
"Person 2"
{
"age" "25"
"name" "Jamie"
"gender" "helicopter"
}
}
答案 0 :(得分:0)
我试着在C ++ 11/14中使用正则表达式。但说实话,这不是一个有趣的问题,正则表达式可能是这项工作的错误工具。
我想出了这个代码,可以将您的示例输入转换为有效的JSON:
#include <iostream>
#include <regex>
using namespace std;
int main (int argc, const char * argv[]) {
std::string test = R"(
"People"
{
"Person 1"
{
"age" "34"
"name" "John"
"gender" "male"
"skills"
{
"skill 1" "Intelligent"
"skill 2" "Wise"
"skill 3" "Buff as a bear!"
}
}
"Person 2"
{
"age" "25"
"name" "Jamie"
"gender" "helicopter"
}
}
)";
regex reg(R"(("[^"]+")\s+("[^"]+"))");
test = std::regex_replace(test, reg, "$1:$2,");
regex reg2(R"((?:\A|\n)\s*("[^"]+")\s*(\n|\Z))");
test = std::regex_replace(test, reg2, "$1:");
regex reg3(R"(}\s*("[^"]+"):\s*\{)");
test = std::regex_replace(test, reg3, "},\n$1: {");
regex reg4(R"(,\s*})");
test = std::regex_replace(test, reg4, "}");
cout << "{" << test << "}" << endl;
}
输出:
{"People":{"Person 1": {
"age":"34",
"name":"John",
"gender":"male","skills": {
"skill 1":"Intelligent",
"skill 2":"Wise",
"skill 3":"Buff as a bear!"}
},
"Person 2": {
"age":"25",
"name":"Jamie",
"gender":"helicopter"}
}
}
但是,您的里程可能因不同的,更复杂的输入而有所不同。