如何使用 json.hpp

问题描述

我正在使用以下库来处理 JSON 内容https://github.com/nlohmann/json

我有一个json配置文件,其中部分内容如下:

 "mqtt_config": {
        "host": "my_mqtt_broker.com","password": "admin","port": 8883,"tls": true,"username": "admin"
    }

我希望能够从我的 C/C++ 应用程序中更改这些值中的任何一个

我正在做的事情如下,例如尝试更改端口号:

std::ifstream in(configFile);
json infile = json::parse(in);

infile["mqtt_config.port"] = 1883;

std::ofstream out(configFile);
out << std::setw(4) << infile << std::endl;

in.close();
out.close();

然而,这并不像我期望的那样表现,它只是将 "mqtt_config.port": 1883 添加文件中的单独一行,而不是像我期望的那样嵌套?有谁知道如何解决这个问题?提前致谢。

解决方法

您似乎误解了 API,infile["mqtt_config.port"] = 1883; 此语句将添加一个带有字符串 mqtt_config.port 的键

它可以通过以下方式修复

infile["mqtt_config"]["port"] = 1883;

Online demo