Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON string with jsoncpp

Tags:

c++

json

jsoncpp

I'm trying to parse a JSON string encoded with PHP and sent over TCP to a C++ client.

My JSON strings are like this:

{"1":{"name":"MIKE","surname":"TAYLOR"},"2":{"name":"TOM","surname":"JERRY"}}

On the C++ client I'm using the jsoncpp libraries:

void decode()
{
    string text =     {"1":{"name":"MIKE","surname":"TAYLOR"},"2":{"name":"TOM","surname":"JERRY"}};
    Json::Value root;
    Json::Reader reader;
    bool parsingSuccessful = reader.parse( text, root );
    if ( !parsingSuccessful )
    {
        cout << "Error parsing the string" << endl;
    }
    const Json::Value mynames = root["name"];
    for ( int index = 0; index < mynames.size(); ++index )  
    {
        cout << mynames[index] << endl;
    }
}

The problem is that I'm not getting anything as output, not even the error about the parsing(if any). Could you possibly help me to understand what I'm doing wrong ?

like image 727
Podarce Avatar asked Nov 14 '17 10:11

Podarce


People also ask

How do I parse a string in JSON?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

What is JSON parsing example?

JSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server's data, and it is a better alternative for XML. This is because JSON is a lightweight and structured language.

How do I read a JSON file in CPP?

Simple JSON Parser in C++ using JsonCpp library We can use Json::Reader and Json::Writer for reading and writing in JSON files. Json::reader will read the JSON file and will return the value as Json::Value . Parsing the JSON is very simple by using parse() .


1 Answers

You can also read from a stringstream:

std::stringstream sstr(stringJson);
Json::Value json;
sstr >> json;
like image 152
waynix Avatar answered Sep 16 '22 20:09

waynix