| 试题编号: | 201709-3 |
| 试题名称: | JSON查询 |
| 时间限制: | 1.0s |
| 内存限制: | 256.0MB |
| 问题描述: |
问题描述 JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,可以用来描述半结构化的数据。JSON 格式中的基本单元是值 (value),出于简化的目的本题只涉及 2 种类型的值: 输入格式 第一行是两个正整数 n 和 m,分别表示 JSON 数据的行数和查询的个数。 输出格式 对于输入的每一个查询,按顺序输出查询结果,每个结果占一行。 样例输入 10 5 样例输出 STRING John 评测用例规模与约定 n ≤ 100,每行不超过 80 个字符。 |
这道题我开始是用的树去存储,但是发现这样代码量会特别大,二刷的时候用map去做,简单不少。为了能够满足多层次结构,可以利用一个index变量去记录层数,一个string数组strx[index]去记录当前层数的key值。
#include <iostream>
#include <map>
#include <string>
using namespace std;
const int MAXN = 100;
map<string, string> mp;
string strx[MAXN];
string getstr(string s, int & i) {
string strout;
for (i = i + 1;; i++) {
if (s[i] == '\\') {
strout += s[++i];
}
else if (s[i] == '"') {
break;
}
else
strout += s[i];
}
return strout;
}
int main()
{
freopen("in.txt", "r", stdin);
int n, m;
cin >> n >> m;
string strall;
for (int i = 0; i <= n; i++) {
string str ;
getline(cin, str);
for (string::iterator it = str.begin(); it != str.end();it++) {//删除所有的空格
if (*it == ' ') {
str.erase(it);
}
}
strall += str;
}
bool key = 1;//key为1表示可以读入key值
int index = 1;
for (int i = 0; i < strall.size(); i++) {
string str1, str2;
if (strall[i] == '"' && key) {
str1 = getstr(strall, i);
if (index == 1) {
strx[index] = str1;
}
else
strx[index] = strx[index - 1] + "." + str1;
key = !key;
}
else if (strall[i] == ':') {
i++;
if (strall[i] == '"') {
str2 = getstr(strall, i);
key = !key;
mp[strx[index]] = "STRING " + str2;
}
else if (strall[i] == '{') {
mp[strx[index]] = "OBJECT";
index++;
key = !key;
}
}
else if(strall[i] == ',')
continue;
else if (strall[i] == '}') {
index--;
}
}
for (int i = 0; i < m; i++) {
string str1;
cin >> str1;
if (mp.find(str1) != mp.end())
cout << mp[str1] << endl;
else
cout << "NOTEXIST" << endl;
}
}
本文介绍了一种使用C++解析和查询JSON数据的方法,重点在于如何处理JSON对象和字符串,实现多层次结构的查询,适用于半结构化数据的处理。
&spm=1001.2101.3001.5002&articleId=88395489&d=1&t=3&u=9efefdd7f9fe44ff8cc4831b7b0f0ce0)
1675

被折叠的 条评论
为什么被折叠?



