Question

I have a sample file "sample.json" which contains 3 json objects

{"A":"something1","B":"something2","C":"something3","D":"something4"}{"A":"something5","B":"something6","C":"something7","D":"something8"}{"A":"something9","B":"something10","C":"something11","D":"something12"}

(there is no newline in above file)

I want to read all three json objects using jsoncpp.

I'm able to read the first object but not after it.

Here is relevant portion of my code

    Json::Value root;   // will contains the root value after parsing.
    Json::Reader reader;
    std::ifstream test("sample.json", std::ifstream::binary);
    bool parsingSuccessful = reader.parse(test, root, false);
    int N = 3;
    if (parsingSuccessful)
    {
         for (size_t i = 0; i < N; i++)
         {
                std::string A= root.get("A", "ASCII").asString();
                std::string B= root.get("B", "ASCII").asString();
                std::string C= root.get("C", "ASCII").asString();
                std::string D= root.get("D", "ASCII").asString();
               //print all of them
        }
    }
Was it helpful?

Solution

I believe your JSON file is syntactically invalid. See www.json.org. Your file should contain a single object or array, e.g. in your case it should like this:

[{"A":"something1","B":"something2","C":"something3","D":"something4"},
 {"A":"something5","B":"something6","C":"something7","D":"something8"}, 
 {"A":"something9","B":"something10","C":"something11","D":"something12"}]

Then you can access each object of the array in your loop:

for (Json::Value::ArrayIndex i = 0; i != root.size(); i++)
{
    std::string A = root[i].get("A", "ASCII").asString();
    // etc.
}

OTHER TIPS

Here is a solution to the question, pretending there are newlines between each object (and no line is blank or malformed):

// Very simple jsoncpp test
#include <json/json.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
    Json::Value root;
    Json::Reader reader;
    ifstream test("sample.json", ifstream::binary);
    string cur_line;
    bool success;

    do {
        getline(test, cur_line);
        cout << "Parse line: " << cur_line;
        success = reader.parse(cur_line, root, false);
        cout << root << endl;
    } while (success);

    cout << "Done" << endl;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top