csp201709-3 json查询

本文介绍了一个用于在复杂JSON字符串中查找指定路径值的C++算法。该算法通过一系列辅助函数实现对JSON字符串的解析和遍历,能够准确地定位到指定路径并返回对应的值类型或字符串内容。

转载自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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值