Json: [question] how to get a string value by pointer

Created on 9 Aug 2017  路  4Comments  路  Source: nlohmann/json

I wrapped a C lib for using json.hpp, like this:

json_string = {"file":"/opt/test.conf"}

set json_string to a static json object

static json para = json::parse(json_string);

`
extern "C" const char*

get_json_string()

{

if (para["file"].is_string())     

{                        

    return para["file"].get<std::string>().c_str();      

}

}
`

but actually, get_json_string cannot get the real address of para, so how to get a string value in this way ?

I don't want to use strcpy like this:
`
get_json_string(char* value)

{

if (para["file"].is_string())

{

    strcpy(value, para["file"].get<std::string>().c_str());

}

}
`

question proposed fix

All 4 comments

I find a way like this:

`
extern "C" const char*

get_json_string()

{

if (para["file"].is_string())

{

return para["file"].get<json::string_t*>()->c_str();      
 ----  or ----
return para["file"].get_ptr<json::string_t*>()->c_str();

}

}
`

now I can get the correct data, is that right ?

and

get<json::string_t*>()->c_str(); or get_ptr<json::string_t*>()->c_str();

which one is corret, or better ?

You should use get_ptr to be sure no copies are made:

return get_ptr<json::string_t*>()->c_str();

Does this solve the issue?

many thanks, issue has been solved ^^

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MariaRamos89 picture MariaRamos89  路  4Comments

zkelo picture zkelo  路  3Comments

mlund picture mlund  路  4Comments

Fonger picture Fonger  路  4Comments

garethsb-sony picture garethsb-sony  路  4Comments