Jsonパーサの自作ーその2


【経緯】:
令和2年1月28日火曜日。Json のパーサーですが、やっとそれらしい形が見えてきました。
main 関数でキックして、パーサーを再帰します。
キーとバリューという呼び方が正しいかどうかわかりませんが、
map の要領で考えると、そういう言葉が当てはまるのでそういう呼び方をしています。
パーサーの中で、キーとバリューを変数に格納する関数を別途作りました。
設計が乱れて、試行錯誤の力技で解答に結びついたところもあって、かなり疲れました。
文書の解析をするのも結構大変ですね。
次回は、C++の vector を使って、利用できるデータに加工します。


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


0.コーディング


#include <stdio.h> #include <stdlib.h> #include <string.h> void GetKeyValue(const char *str, char *value, char *key) { int len = 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'; printf("key = %s\n", key); 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<h;len) { value[j] = str[i]; i++; j++; } value[j] = '\0'; printf("value = %s\n", value); } i++; } } void ParseJson(const char *str, char *element) { int len = 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); ParseJson(value, element); 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); ParseJson(value, element); 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]; char key[1024]; char value[1024]; ParseJson(str, element); return 0; } /* { "match request": "OK", "size": 3, "board": { "1": { "row": 3, "col": 3 }, "2": { "row": 4, "col": 4 }, "3": { "row": 5, "col": 5 } } } */