CCF计算机职业资格认证考试题解系列文章为meelo原创,请务必以连接形式注明本文地址html
json是一个递归数据结构,所以可使用函数的递归调用来进行解析。ios
每一类数据对应一个解析函数,代码中parseString实现解析字符串的功能,parseObject实现解析对象的功能。编程
解析函数的主体功能就是依次遍历每个字符,根据字符判断是不是字符串的开始、对象的开始……并进行相应的处理。json
json是一个键值对的结构,所以能够用map存储。map的键能够用查询的格式,用小数点.来分隔多层的键。数据结构
C++函数
#include <iostream> #include <cassert> #include <map> using namespace std; string parseString(string &str, int &i) { string tmp; if(str[i] == '"') i++; else assert(0); while(i < str.size()) { if(str[i] == '\\') { i++; tmp += str[i]; i++; } else if(str[i] == '"') { break; } else { tmp += str[i]; i++; } } if(str[i] == '"') i++; else assert(0); return tmp; } void parseObject(string &str, string prefix, map<string, string> &dict, int &i) { if(str[i] == '{') i++; else assert(0); string key, value; bool strType = false; // false:key, true:value while(i < str.size()) { if(str[i] == '"') { string tmp = parseString(str, i); if(strType) { // value value = tmp; //cout << key << " " << value << "\n"; dict[key] = value; } else { // key key = prefix + (prefix==""?"":".") + tmp; } } else if(str[i] == ':') { strType = true; i++; } else if(str[i] == ',') { strType = false; i++; } else if(str[i] == '{') { dict[key] = ""; parseObject(str, key, dict, i); } else if(str[i] == '}') { break; } else { i++; } } if(str[i] == '}') i++; else assert(0); } int main() { int N, M; cin >> N >> M; string json; if(cin.peek()=='\n') cin.ignore(); for(int n=0; n<N; n++) { string tmp; getline(cin, tmp); json += tmp; } map<string, string> dict; int i = 0; parseObject(json, "", dict, i); string query; for(int m=0; m<M; m++) { getline(cin, query); if(dict.find(query) == dict.end()) { cout << "NOTEXIST\n"; } else { if(dict[query] == "") { cout << "OBJECT\n"; } else { cout << "STRING " << dict[query] << "\n"; } } } }