How to iterate JSON array in C++ using Boost.JSON
You can use a standard for iteration loon on j.as_array() in order to iterate all values in the given JSON array:
iterate_json_array.cpp
for (auto& value : json.as_array()) {
std::cout << value.as_int64() << std::endl;
}Full example:
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 using
compile_json.sh
g++ -o json json.cpp -lboost_jsonThis will print
example.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