Some data files that I need to read / parse have headers in the style:
level0var = value0
level0var.level1field = value1
level0var.level1array[11].level2field = value2
...
In other words, they look like nested C-style structs and arrays, but none of these are declared in the header: I need to infer the structure as I read.
My plan was to use the famous nlohmann::json
library to store this, because its flexibility would allow me to change the structure of the data during parsing, and save the header in a more readable form.
I read the assignments in as lhs = rhs
, and both of those are strings. Given json header;
to deal with the unknown, variable depth of the structures I want to do something like
// std::string lhs = "level0var.level1field.level2field";
// std::string rhs = "value2";
auto current_level = header;
while ( lhs != "" ) {
auto between = lhs.substr ( 0, lhs.find_first_of ( "." ) );
lhs.erase ( 0, lhs.find_first_of ( "." ) + 1 );
if ( lhs == between ) break;
current_level [ between ] = json ( {} );
current_level = current_level [ between ];
}
current_level = rhs;
std::cout << std::setw(4) << header;
for every line that has at least 1 struct level (leaving the arrays for now).
The strange thing is that using this loop, the only thing the last line returns is null
, whereas when I use
header [ "level0var" ] [ "level1field" ] [ "level2field" ] = rhs;
std::cout << std::setw(4) << header;
it gives the expected result:
{
"level0var": {
"level1field": {
"level2field": "value2"
}
}
}
Is there a way to build this hierarchical structure iteratively (without supplying it as a whole)? Once I know how to do structs, I hope the arrays will be easy!
The example I made at work does not run on coliru (which does not have the JSON library I guess).