Home > database >  How can I write field value to a json file with boost?
How can I write field value to a json file with boost?

Time:07-25

I have some json file:

{
    ....
    ....
    "frequency_ask": 900
}

and need to change field frequency_ask to 1200 for example.

I called my function

void setFieldToJson(std::string json, std::string field, int value)
{
    boost::property_tree::ptree pt;
    pt.put(field, value);
    std::ostringstream json;

    boost::property_tree::write_json(json, pt);
}

with next:

setFieldToJson("../config_files/device.json", "frequency_ask", 1200);

but doesn't work.

How can I make it correct?

CodePudding user response:

Your problem is most likely that you're using Property Tree, which is NOT a JSON library.

Alternatively, it could be that your input is not valid JSON.

Here's my take using Boost JSON:

enter image description here

  • Related