Jsonパーサの自作ーその2


【経緯】:
令和2年1月28日火曜日。Json のパーサーですが、テストは行っていませんが、ドラフトが出来上がりました。
たった200行程度書くのに一週間も費やしてしまいました。
ざっと見てみると、大したことはしてないのですが、文字列処理は難しいですね。
かなり苦戦しました。
std::map<std::strin, std::strin>を使いました。
STLのコレクションみたいなところは、可変長に値を格納できるところが便利ですね。
元のプロダクトに戻ります。
お疲れさまでした。


Jsonのパーサです。
未完成ですが、動作実績ありです。


0.コーディング


#include <iostream> #include <map> #include <cstring> void GetKeyValue(const char *str, char *value, char *key, std::map<std::string, std::string> *pair) { int len = std::strlen(str); int i = 0; int status = 0; while(i<len) { if('\"' == str[i] && 0 == status) { int j = 0; i++; while(i<len) { if('\"' == str[i]) { i++; break; } key[j] = str[i]; i++; j++; } key[j] = '\0'; std::cout << key << std::endl; status = 2; } if('\"' == str[i] && 1 == status) { status = 2; } if(':' == str[i] && 2 == status) { i++; status = 3; } if(3 == status) { int j = 0; while(i<len) { value[j] = str[i]; i++; j++; } value[j] = '\0'; std::cout << value << std::endl; } pair->insert(std::make_pair(key, value)); i++; } } void ParseJson(const char *str, char *element, std::map *pair) { int len = std::strlen(str); int status = 0; int i = 0; int k = 0; int depth = 0; int dig = 0; int s = 0; char key[1024]; char value[1024]; while(i<len) { if('\"' == str[i] && 0 == status) { dig = depth; status = 1; } if('\"' == str[i] && 1 == status) { status = 2; } if(':' == str[i] && 2 == status) { status = 3; } if('{' == str[i]) { depth++; } if('}' == str[i]) { depth--; } if('}' == str[i] && 0 == depth && 2 < status) { int j = 0; while(k<i) { element[j] = str[k]; k++; j++; } element[j] = '\0'; GetKeyValue(element, value, key, pair); ParseJson(value, element, pair); i++; } if(',' == str[i] && 3 == status && dig == depth) { int j = 0; while(k<i) { element[j] = str[k]; k++; j++; } element[j] = '\0'; GetKeyValue(element, value, key, pair); ParseJson(value, element, pair); i++; status = 0; } i++; } } int main(void) { const char *str = "{\"match request\": \"OK\", \"size\": 3, \"board\": {\"1\": {\"row\": 3, \"col\": 3}, \"2\": {\"row\": 4, \"col\": 4}, \"3\": {\"row\": 5, \"col\": 5}}}"; const char *str1 = "{\"request\":100}"; char element[1024]; std::map<std::string, std::string> p; int size = p.size(); std::cout << "size = " << size << std::endl; ParseJson(str, element, &p); size = p.size(); std::cout << "size = " << size << std::endl; return 0; } /* { "match request": "OK", "size": 3, "board": { "1": { "row": 3, "col": 3 }, "2": { "row": 4, "col": 4 }, "3": { "row": 5, "col": 5 } } } */