0

Hi I have following string

{
"data1" : "sample data",
"data2" : "sample data2"
}

I want to split the above string using string library to

data1
sample data

Following is the code that I came up with but it's only splitting left and not right. above data is stored in buffer and iterated by line_number.

if(pos != std::string::npos)
            {
                newpos = buffer[line_number].find_first_of(":",pos);
                token = buffer[line_number].substr(pos + 1,newpos-pos-1);
                pos = newpos + 1;
                std::cout << token << std::endl;
            }

Help would be really appreciated.

2
  • 3
    If you want to parse json you should use json parser Commented Oct 12, 2014 at 19:04
  • @Lol4t0 I just want to specifically separate out key and value Commented Oct 12, 2014 at 19:10

1 Answer 1

2

Very simple parser might look like this:

#include <iostream>
#include <string>
#include <vector>
#include <map>

using namespace std;

static string& strip(string& s, const string& chars = " ")
{
        s.erase(0, s.find_first_not_of(chars.c_str()));
        s.erase(s.find_last_not_of(chars.c_str()) + 1);
        return s;
}

static void split(const string& s, vector<string>& tokens, const string& delimiters = " ")
{
        string::size_type lastPos = s.find_first_not_of(delimiters, 0);
        string::size_type pos = s.find_first_of(delimiters, lastPos);
        while (string::npos != pos || string::npos != lastPos) {
                tokens.push_back(s.substr(lastPos, pos - lastPos));
                lastPos = s.find_first_not_of(delimiters, pos);
                pos = s.find_first_of(delimiters, lastPos);
        }
}

static void parse(string& s, map<string,string>& items)
{
        vector<string> elements;
        s.erase(0, s.find_first_not_of(" {"));
        s.erase(s.find_last_not_of("} ") + 1);
        split(s, elements, ",");
        for (vector<string>::iterator iter=elements.begin(); iter != elements.end(); iter++) {
                vector<string> kv;
                split(*iter, kv, ":");
                if (kv.size() != 2) continue;
                items[strip(kv[0], " \"")] = strip(kv[1], " \"");
        }
}

int
main()
{
        string data = "  {  \"key1\"  :  \"data1\"  ,  \"key2\"  :  \"data2\"    }  ";
        map<string,string> items;
        parse(data, items);

        for (map<string,string>::iterator iter=items.begin(); iter != items.end(); iter++) {
                cout << "key=" << (*iter).first << ",value=" << (*iter).second << endl;
        }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.