我有一个看起来像这样的翻译文件:
#: this is just some comment
msgid ""
"this is a line.n"
"this is a newline.n"
"this is another newLine".
msgstr ""
"this can be filled in.n"
"or left blank."
#: just another comment
msgid "Pizza"
msgstr ""
您可以看到msgid
可以是多行的或单键的。msgstr
。
我所有的翻译文件看起来都这样。我将如何使用上述数据示例创建一个包含两个键的JSON对象:
[
{
"msgid": "this is a line.nthis is a newline.nthis is another newLine.",
"msgstr": "this can be filled in.n or left blank."
},
{
"msgid": "Pizza",
"msgstr": ""
}
]
我可以访问我知道如何使用的JSON LIBARY。我正在努力通过数据循环(每个)循环循环。
目前我有此代码:
std::ifstream input(findFile("language.po"));
Json::Value jsonRoot = Json:arrayValue;
for( std::string line; getline( input, line ); )
{
Json::Value Translation = Json::objectValue;
if(line.find("msgid") == 0) {
//messageId found
Translation["msgid"] = line;
} else if(line.find("msgstr") == 0) {
//translated string was found
Translation["msgstr"] = line;
}
jsonRoot.append(Translation);
}
但这为我不想要的每一行创建了一个新的JSON数组。
此刻,当前输出(未测试)应如下:
[
{
"msgid": ""
},
{
"msgstr": ""
},
{
"msgid": "Pizza"
},
{
"msgstr": ""
}
]
无论每行的内容如何,您的循环都将每行添加到数组中。您需要的是状态计算机,因此您只需将完整的对象添加到数组,您需要将持续行添加到以前的线上,直到到达下一个字段启动为止,并且您需要分析行以删除行前缀和报价。<<<<<<<<<<<<<<<<<<<<<<<<<</p>
尝试更多类似的东西:
std::ifstream input(findFile("language.po").string());
std::string msgid, msgstr;
std::string *field = NULL;
std::string::size_type start, end;
Json::Value jsonRoot = Json::arrayValue;
for( std::string line; std::getline( input, line ); )
{
if (line.compare(0, 1, "#") == 0)
continue;
if (line.compare(0, 6, "msgid ") == 0)
{
if (!msgid.empty())
{
Json::Value Translation = Json::objectValue;
Translation["msgid"] = msgid;
Translation["msgstr"] = msgstr;
jsonRoot.append(Translation);
}
msgid.clear();
msgstr.clear();
field = &msgid;
start = 6;
}
else if (!field)
{
continue;
}
else if (line.compare(0, 7, "msgstr ") == 0)
{
field = &msgstr;
start = 7;
}
else
{
start = 0;
}
start = line.find('"', start);
if (start == std::string::npos)
continue;
++start;
end = line.find('"', start);
if (end != std::string::npos)
*field += line.substr(start, end-start);
else
*field += line.substr(start);
}
if (!msgid.empty())
{
Json::Value Translation = Json::objectValue;
Translation["msgid"] = msgid;
Translation["msgstr"] = msgstr;
jsonRoot.append(Translation);
}
我会写一台简单的状态计算机:
enum class State { INIT, ID, STR } state = State::INIT;
std::string buffer;
while (!end_of_file()) {
auto s = get_next_line();
if (is_comment(s)) {
// do nothing
} else if (is_msgid(s)) {
if (state != State::STR) {
buffer += s; // depending on how you read a line, you may have to add EOL here
} else {
put_msgid_into_json(buffer);
buffer = s;
}
state = State::ID;
} else if (is_msgstr(s)) {
if (state != State::ID) {
buffer += s; // depending on how you read a line, you may have to add EOL here
} else {
put_msgstr_into_json(buffer);
buffer = s;
}
state = State::STR;
}
}
if (state == State::ID) {
put_msgid_into_json(buffer);
} else if (state == State::STR) {
put_msgstr_into_json(buffer);
}