如何使用nlohmann json解析对象数组并访问layer、properties等字段
nlohmann json多层字段访问解决方案
你当前的遍历逻辑有误,根JSON本身是数组类型,items()是JSON对象(键值对结构)的遍历方法,你直接遍历根数组的每个元素,就能通过字段名访问到所有属性。
以下是可直接运行的示例代码:
#include <nlohmann/json.hpp> #include <iostream> using json = nlohmann::json; int main() { // 替换为你自己的JSON解析逻辑,这里默认你已经把内容解析到变量j中 json j; // 遍历根数组的每个元素,每个元素就是包含所有字段的单个特征对象 for (auto& feature : j) { // 访问根层级的type字段 std::string type = feature["type"]; std::cout << "type: " << type << std::endl; // 访问根层级的properties字段 json properties = feature["properties"]; std::cout << "properties: " << properties.dump() << std::endl; // 访问layer下的id字段 std::string layer_id = feature["layer"]["id"]; std::cout << "layer id: " << layer_id << std::endl; // 访问layer下paint的fill-opacity字段 double fill_opacity = feature["layer"]["paint"]["fill-opacity"]; std::cout << "fill opacity: " << fill_opacity << std::endl; // 直接打印完整layer对象,dump的参数是缩进空格数 std::cout << "full layer content: " << feature["layer"].dump(4) << std::endl; std::cout << "--------------------------" << std::endl; } return 0; }
补充注意事项
- 如果你要避免字段不存在抛出异常,可以先通过
contains()方法判断字段是否存在再访问:
if (feature.contains("layer") && feature["layer"].contains("id")) { std::string layer_id = feature["layer"]["id"]; }
- 也可以用
get<T>()方法显式指定类型转换,避免隐式转换出错:
double fill_opacity = feature["layer"]["paint"]["fill-opacity"].get<double>();
内容的提问来源于stack exchange,提问作者dan
相关产品推荐
相关产品推荐

