Open xkungfu opened 2 years ago
Try this:
For yaml1:
WsjcppYaml yaml;
std::vector<std::string> vKeys = yaml["list"].keys();
For yaml2:
WsjcppYaml yaml;
std::vector<std::string> vKeys = yaml.getCursor().keys();
More samples
std::string sTest =
"'2021-10-08':\n"
" - code: '300209'\n"
" focusstr: ''\n"
" - code: '300047'\n"
" focusstr: ''\n"
" - code: '300970'\n"
" focusstr: ''\n"
" - code: '300288'\n"
" focusstr: ''\n"
"'2021-10-11':\n"
" - code: '300162'\n"
" focusstr: ''\n"
" - code: '300209'\n"
" focusstr: ''\n"
" - code: '300972'\n"
" focusstr: ''\n"
" - code: '300159'\n"
" focusstr: ''\n"
;
WsjcppYaml yaml2;
if (!yaml2.loadFromString("test", sTest, sError)) {
return -1;
}
WsjcppYamlCursor cur = yaml2.getCursor();
std::vector<std::string> vKeys = cur.keys();
for (int i = 0; i < vKeys.size(); i++) {
std::string sKey = vKeys[i];
int nCount = cur[sKey].size(); // musts array
for (int n = 0; n < nCount; n++) {
WsjcppYamlCursor el = cur[sKey][n];
std::cout
<< "code = " << el["code"].valInt()
<< "; focusstr = " << el["focusstr"].valStr()
<< ";"
<< std::endl;
}
}
output:
code = 300209; focusstr = ;
code = 300047; focusstr = ;
code = 300970; focusstr = ;
code = 300288; focusstr = ;
code = 300162; focusstr = ;
code = 300209; focusstr = ;
code = 300972; focusstr = ;
code = 300159; focusstr = ;
I will try and post codes tomorrow. thank you very much!
You welcome!
WsjcppYamlCursor el = cur[sKey][n];
I just tried to write a loop for almost one hour and haven't got a right output, then find your code. I am a newbie. thanks for your detailed guide step by step!
one more question: python yaml generate the format without indent, or indent after "-", like below:
with open(path, 'w') as f:
yaml.dump(a_dict, f, default_flow_style=False, sort_keys=False)
generate result like:
std::string sTest =
"'2021-10-08':\n"
"-code: '300209'\n"
" focusstr: ''\n"
"-code: '300047'\n"
" focusstr: ''\n"
"-code: '300970'\n"
" focusstr: ''\n"
"-code: '300288'\n"
" focusstr: ''\n"
"'2021-10-11':\n"
"-code: '300162'\n"
" focusstr: ''\n"
"-code: '300209'\n"
" focusstr: ''\n"
"-code: '300972'\n"
" focusstr: ''\n"
"-code: '300159'\n"
" focusstr: ''\n"
;
with open(path, 'w') as f:
yaml.dump(a_dict, f, indent=4, default_flow_style=False, sort_keys=False)
generate result like:
std::string sTest =
"'2021-10-08':\n"
"- code: '300209'\n"
" focusstr: ''\n"
"- code: '300047'\n"
" focusstr: ''\n"
"- code: '300970'\n"
" focusstr: ''\n"
"- code: '300288'\n"
" focusstr: ''\n"
"'2021-10-11':\n"
"- code: '300162'\n"
" focusstr: ''\n"
"- code: '300209'\n"
" focusstr: ''\n"
"- code: '300972'\n"
" focusstr: ''\n"
"- code: '300159'\n"
" focusstr: ''\n"
;
It seems with indent or without indent are all valid, but wsjcpp-yaml need indent at the line start of array elements.
@xkungfu sorry for a longtime.... so... python can parse this?
yaml 1:
yaml2:
want to get how many date string in the yaml, and extract all the date strings to a array such as vector. so I can loop the yaml by date keys.
thanks!