json_spirit usage issue

2.5k Views Asked by At

i was able to compile the program successfully but not able to retrieve the values from json object. i am pasting the code below , the code is simple , any help appreciated.

#include <cstdio>
#include <cstring>
#include <json_spirit.h>

using namespace std;
using namespace json_spirit;

//A sample get file request 
char *jsonInput = 
"{\"request\" : { \
                \"service\" : \"fmgr\" \
                \"cookie\"  : \"Abxruyyeziyrolsu\" \
                \"req\"     : \"read\" \
                \"fname\"   : \"Junk.txt\" \
                \"size\"    :  1024 \
                \"data\"    :  \"data\" \
}}";


int main(int argc, char **argv)
{
    Value val;
    const string s = jsonInput;
    read(s, val); //read the jsonInput to the value
    Object obj = val.get_obj();
    std::string service, cookie, req, fname, data;
    uint32_t size;

    for(Object::size_type i = 0; i != obj.size(); ++i) {   
        const Pair& pair = obj[i];
        const string& name  = pair.name_;
        const Value&  value = pair.value_;

        if( name == "service" ) service  = value.get_str();
        else if( name == "cookie") cookie  = value.get_str();
        else if( name == "req" ) req = value.get_str();
        else if( name == "fname" ) fname = value.get_str();
        else if( name == "size" ) size = value.get_int();
        else if( name == "data" ) data = value.get_str();
    }
    std::cout<<service << " " << cookie << " " << req << " " << fname << " " << size << " " << data ;
    return 0;
}
2

There are 2 best solutions below

1
On

To keep things simple, as they should be with json_spirit, try the following after correcting the missing ',' delimiters in the JSON string.

std::string json_input = <your valid JSON string>
json_spirit::Value value;
auto success = json_spirit::read_string(json_input, value);
if (success == true) {
    auto object = value.get_obj();
    for (auto entry : object) {
        if (entry.name_ == "service") service = entry.value_.get_str();
        else if...
        .
        .
    }
}
0
On

There are two things problems:

  1. The jsonInput string is not valid JSON, the commas to separate object pairs are missing.
  2. The next issue is more complicated to explain. The toplevel Value is itself an Object so calling val.get_obj() returns the Object containing all the data. There is only one Pair in this object, named "request". Calling val.get_obj()[0] will retrieve this pair. You then need to get the Object out of this Pair's Value.

    Value val; read(s, val); //read the jsonInput to the value

    const Pair& pair = val.get_obj()[0]; //gets the name:value pair, named "request"

    const Object& obj = pair.value_.get_obj(); //gets the service, cookie... object