c++ 20 解析json
在C++ 20中,可以使用标准库中的JSON库来解析JSON。该库在头文件
以下是一个简单的示例代码,演示如何使用C++ 20标准库解析JSON:
#include <iostream>
#include <json.hpp>
using json = nlohmann::json;
int main() {
std::string jsonData = R"(
{
"name": "John",
"age": 30,
"city": "New York"
}
)";
json j = json::parse(jsonData);
std::cout << "Name: " << j["name"] << std::endl;
std::cout << "Age: " << j["age"] << std::endl;
std::cout << "City: " << j["city"] << std::endl;
return 0;
}
在上面的代码中,我们定义了一个JSON格式的字符串 jsonData,并使用json::parse()函数将其解析为JSON对象j。然后,我们可以使用j对象来访问JSON对象中的属性。
输出结果如下:
Name: John
Age: 30
City: New York
除了访问JSON对象中的属性,还可以使用迭代器遍历JSON对象中的所有属性,如下所示:
for (auto& [key, value] : j.items()) {
std::cout << key << ": " << value << std::endl;
}
输出结果如下:
name: John
age: 30
city: New York
通过这个简单的示例,您可以了解如何在C++ 20中使用标准库中的JSON库来解析JSON。
原文地址: https://www.cveoy.top/t/topic/sFV 著作权归作者所有。请勿转载和采集!