Jsonパーサの自作ーその1


【経緯】:
令和2年1月24日金曜日。コードを書いた日はこの日だったが、このドキュメントを書くのが1月26日日曜日になってしまった。
ドキュメントを書く間にもコード書きの進捗があったので、現在の最新版ではないですが、途中経過を載せておきます。
改めてみると、結構回りくどいことをしています。パターンを用意しておいて、パースする文字列がそのパターンにマッチしていれば処理を行うみたいなことをしているので、
もし、イレギュラーがあると、処理をしてくれません。
ある程度進んだところで理解が深まりましたが、再帰的に処理をするアルゴリズムが必要です。自動的に構文を解釈する仕組みが必要です。
参考までに。次回の更新が待たれます。


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


0.コーディング


#include <stdio.h>
#include <string.h> int SyntaxSearch(const char *str) { char *syntaxPattern_A = "{\"\":\"\"}"; char *syntaxPattern_B = "{\"\":}"; int ret = -1; char pattern[16]; int len = strlen(str); int i = 0; int j = 0; while(i<len) { if('{' == str[i]) { pattern[j++] = '{'; } else if('}' == str[i]) { pattern[j++] = '}'; } else if(':' == str[i]) { pattern[j++] = ':'; } else if('\"' == str[i]) { pattern[j++] = '\"'; } i++; } pattern[j] = '\0'; if(0 == strcmp(pattern, syntaxPattern_A)) { ret = 0; } else if(0 == strcmp(pattern, syntaxPattern_B)) { ret = 1; } else { ret = 2; } return ret; } int IndexPositionCheck(const char *str, int save, char target) { int i = save; while(i < 1024 - save) { if(target == str[i]) { i++; break; } i++; } return i; } int GetKeyValueInJson(const char* str, int save, char *key) { int i = save; int j = 0; while(i < 1024 - save) { if('\"' == str[i] || '}' == str[i]) { break; } key[j++] = str[i]; i++; } key[j] = '\0'; printf("%s\n", key); return i; } int main(void) { const char *str1 = "{\"request\":\"match request\"}"; const char *str = "{\"request\":100}"; const char *syntaxPattern_A = "{\"\":\"\"}"; const char *syntaxPattern_B = "{\"\":}"; int save = 0; char key[512]; char value[512]; int pattern = SyntaxSearch(str); switch(pattern) { case 0: // { save = IndexPositionCheck(str, save, syntaxPattern_A[0]); // \" save = IndexPositionCheck(str, save, syntaxPattern_A[1]); // Get "Key" save = GetKeyValueInJson(str, save, key); // \" save = IndexPositionCheck(str, 0, syntaxPattern_A[2]); // : save = IndexPositionCheck(str, save, syntaxPattern_A[3]); // \" save = IndexPositionCheck(str, save, syntaxPattern_A[4]); // Get "Value" save = GetKeyValueInJson(str, save, value); // \" save = IndexPositionCheck(str, save, syntaxPattern_A[5]); // } save = IndexPositionCheck(str, save, syntaxPattern_A[6]); break; case 1: // { save = IndexPositionCheck(str, save, syntaxPattern_B[0]); // \" save = IndexPositionCheck(str, save, syntaxPattern_B[1]); // Get "Key" save = GetKeyValueInJson(str, save, key); // \" save = IndexPositionCheck(str, 0, syntaxPattern_B[2]); // : save = IndexPositionCheck(str, save, syntaxPattern_B[3]); // Get "Value" save = GetKeyValueInJson(str, save, value); // } save = IndexPositionCheck(str, save, syntaxPattern_B[4]); break; } return 0; }