std::string json_str = R"({"code":200,"data":[{"id":1},{"id":2}]})"; json j = json::parse(json_str);去除code字段
时间: 2023-07-19 09:39:08 浏览: 39
可以使用 `erase` 函数来去除 JSON 对象中的 `code` 字段,示例如下:
```cpp
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
std::string json_str = R"({"code":200,"data":[{"id":1},{"id":2}]})";
json j = json::parse(json_str);
j.erase("code");
std::cout << j.dump() << std::endl;
return 0;
}
```
输出结果为:
```
{
"data": [
{
"id": 1
},
{
"id": 2
}
]
}
```
相关问题
{"code":200,"data":[{"id":1},{"id":2}]} 用nlohmann-json获取id为2的json obeject
假设你已经用 nlohmann-json 将该 json 字符串解析为一个 json 对象,可以使用以下代码来获取 id 为 2 的 json 对象:
```cpp
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
std::string json_str = R"({"code":200,"data":[{"id":1},{"id":2}]})";
json j = json::parse(json_str);
// 获取 data 数组中 id 为 2 的 json object
json id_2_obj;
for (const auto& item : j["data"]) {
if (item["id"] == 2) {
id_2_obj = item;
break;
}
}
std::cout << id_2_obj.dump() << std::endl; // 输出:{"id":2}
return 0;
}
```
在上述代码中,我们首先定义了一个 json 对象 `j`,并将 json 字符串解析为该对象。然后使用 for 循环遍历 `j["data"]` 数组中的每个元素,找到 id 为 2 的 json object 并赋值给 `id_2_obj` 变量。最后使用 `dump()` 函数将 `id_2_obj` 对象转换为 json 字符串并输出。
httplib::Client 的 Post json数据
使用 httplib 库的 Client 类可以通过 POST 请求发送 JSON 数据,具体实现如下:
```c++
#include <iostream>
#include <httplib.h>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
// 创建 JSON 数据
json data = {
{"name", "Tom"},
{"age", 20},
{"gender", "male"}
};
// 转换为字符串
std::string json_str = data.dump();
// 创建 httplib::Client 对象
httplib::Client cli("localhost", 8080);
// 构造 POST 请求
auto res = cli.Post("/api", json_str, "application/json");
if (res) {
if (res->status == 200) {
std::cout << res->body << std::endl;
} else {
std::cout << "Error code: " << res->status << std::endl;
}
} else {
std::cout << "Error sending request." << std::endl;
}
return 0;
}
```
其中,`json` 类型是 `nlohmann/json` 库中的一种 JSON 数据类型,可以用来创建和操作 JSON 数据。在这个例子中,我们创建了一个包含名字、年龄和性别的 JSON 数据,并将其转换为字符串。
然后,我们创建了一个 `httplib::Client` 对象,并使用 `Post` 方法发送 POST 请求。第一个参数是请求的路径,第二个参数是要发送的数据,第三个参数是数据类型。
最后,我们检查响应状态码和响应体,并进行相应的处理。