如何在 C++ 中使用 Boost.JSON 遍历 JSON 数组
你可以在 j.as_array() 上使用标准 for 循环来遍历给定 JSON 数组中的所有值:
iterate_json_array.cpp
for (auto& value : json.as_array()) {
std::cout << value.as_int64() << std::endl;
}完整示例:
json_example.cpp
#include <boost/json.hpp>
#include <iostream>
int main()
{
const char* json_str = R"([1, 2, 3, 4, 5])";
boost::json::value j = boost::json::parse(json_str);
if (j.is_array()) {
for (auto& value : j.as_array()) {
std::cout << value.as_int64() << std::endl;
}
}
return 0;
}使用以下命令编译
compile_json.sh
g++ -o json json.cpp -lboost_json这将打印
json_array_output.txt
1
2
3
4
5If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow