json_tokener_parse giving an unexpected output

211 Views Asked by At

Consider the code snippet as shown below

            const char* jstring;
            jstring =  net->Classify(224, 224, imgCUDA,  &confidence);
            std::cout <<jstring << std::endl;
            join_prop = json_tokener_parse( jstring);
            printf("join prop is %s\n",json_object_to_json_string(join_prop));

a call is made to Classify where the json is created and returned. Definition of classify method is

const char* Classify(  uint32_t width, uint32_t height,  float* rgb, float* confidence=NULL);

The snippet within Classify is given below

    jstring =  json_object_to_json_string(properties);
    std::string jstring_str(jstring);
    json_object_put(properties);
    std::cout<< "jstring_str is : "<<jstring_str << std::endl;
    return jstring_str.c_str();

The outputs are printed on to the screen at different points in this code snippet. The outputs are as follows

  1. Within Classify value of jstring_str before return

    jstring_str is : { "head_gear": [ { "confidence": 0.000000, "name": "None" }, { "confidence": 1.000000, "name": "Cap" }, { "confidence": 0.000000, "name": "Helmet" } ] }

2 value at jstring from statement std::cout <<jstring << std::endl;

{ "head_gear": [ { "confidence": 0.000000, "name": "None" }, { "confidence": 1.000000, "name": "Cap" }, { "confidence": 0.000000, "name": "Helmet" } ] }
  1. However at the command of join_prop there seems to be an unexpected output as shown below

join prop is null

I had expected the tokener to parse jstring and convert it to json. It would be really helpful if I can some idea on why I get join prop as null. Any insight would be helpful since I am lost trying to find the cause for this.

The output seems to be a valid json based on https://jsonformatter.curiousconcept.com/

1

There are 1 best solutions below

0
On

This isn't json-c related, you're just misusing str::string. Specifically:

std::string jstring_str(jstring);
...
return jstring_str.c_str();

As you return and leave the scope of that "Classify" function, the jstring_str object will be destroyed, and the memory returned by the c_str() call will no longer be valid.