转载自L_Aster
#include<bits/stdc++.h>
using namespace std;
bool isroot(string & str,size_t pos)
{
int cnt=0;
for(size_t i=0;i<pos;i++)
{
if(str[i]=='{')cnt++;
if(str[i]=='}')cnt--;
}
return cnt==0;
}
vector<string> split(string str)
{
vector<string> vs;
size_t f=str.find(".");
while(f!=string::npos)
{
string tmp=str.substr(0,f);
str=str.substr(f+1);
vs.push_back(tmp);
f=str.find(".");
}
vs.push_back(str);
return vs;
}
string subjsonstr(string str,int lpos)
{
int pcnt=1;
size_t rpos=lpos;
while(pcnt)
{
if(str[rpos]=='{')pcnt++;
if(str[rpos]=='}')pcnt--;
rpos++;
}
return str.substr(lpos,rpos-lpos-1)+",";
}
void search(vector<string>& vs,string jsonstr)
{
size_t i=0;
while(i<vs.size()-1)
{
size_t pos=jsonstr.find(vs[i]+":{");
if(pos==string::npos||!isroot(jsonstr,pos))
{
cout<<"NOTEXIST\n";return;
}
jsonstr=subjsonstr(jsonstr,pos+vs[i].size()+2);
i++;
}
size_t pos=jsonstr.find(vs.back()+":");
if(pos==string::npos||!isroot(jsonstr,pos))
{
cout<<"NOTEXIST\n";
}
else
{
i=pos+vs.back().size()+1;
if(jsonstr[i]=='{')
cout<<"OBJECT\n";
else
{
size_t dp=jsonstr.find(",",i);
if(dp==string::npos)
{
cout<<"NOTEXIST\n";return;
}
string x;
while(i<dp)
x+=jsonstr[i++];
cout<<"STRING "<<x<<endl;
}
}
}
int main()
{
string jsonstr;
int n,m;
cin>>n>>m;
cin.get();
cin.get();
for(int i=0;i<n;i++)
{
char ch;
while((ch=cin.get())!='\n')
{
if(ch==' '||ch=='"')continue;
if(ch=='\\')
{
jsonstr+=cin.get();continue;
}
jsonstr+=ch;
}
}
jsonstr[jsonstr.length()-1]=',';
while(m--)
{
string s;
cin>>s;
vector<string> vs=split(s);
search(vs,jsonstr);
}
}
本文介绍了一个用于在复杂JSON字符串中查找指定路径值的C++算法。该算法通过一系列辅助函数实现对JSON字符串的解析和遍历,能够准确地定位到指定路径并返回对应的值类型或字符串内容。

581

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



