使用nlohmann/json库如何访问JSON嵌套元素?仅能访问根元素
解决nlohmann/json嵌套元素路径访问问题
你的问题在于nlohmann/json的at()方法不直接支持object.array[2].field这种格式的字符串路径,它只能接收单个根级键名。要实现嵌套路径访问,需要手动解析输入的路径字符串,逐层遍历JSON结构。
实现思路
- 拆分路径节点:把输入的路径按
.分割成多个节点(比如object.array[2].field拆分为object、array[2]、field) - 区分节点类型:对每个节点判断是对象的键,还是数组的索引(比如
array[2]要提取数组名array和索引2) - 逐层访问JSON:从根节点开始,依次用每个节点的信息深入到对应层级的元素
修改后的完整代码
#include <iostream> #include <fstream> #include <string> #include <vector> #include <regex> #include <nlohmann/json.hpp> using json = nlohmann::json; // 拆分路径为节点列表 std::vector<std::string> split_path(const std::string& path) { std::vector<std::string> nodes; std::string current; for (char c : path) { if (c == '.' && !current.empty()) { nodes.push_back(current); current.clear(); } else { current += c; } } if (!current.empty()) { nodes.push_back(current); } return nodes; } // 解析单个节点,返回键名和数组索引(如果是数组节点) std::pair<std::string, int> parse_node(const std::string& node) { std::regex array_regex(R"(^(\w+)\[(\d+)\]$)"); std::smatch match; if (std::regex_match(node, match, array_regex)) { return {match[1], std::stoi(match[2])}; } // 不是数组节点,索引返回-1 return {node, -1}; } int main() { std::ifstream file("test3.json"); if (!file.is_open()) { std::cout << "Error: Failed to open file." << std::endl; return 1; } json data; file >> data; std::string access_path; std::cout << "Enter the access path to the nested element (e.g. 'object.array[2].field'): "; std::getline(std::cin, access_path); try { json current = data; std::vector<std::string> nodes = split_path(access_path); for (const std::string& node : nodes) { auto [key, index] = parse_node(node); if (index != -1) { // 数组节点,用索引访问 current = current.at(key).at(index); } else { // 对象节点,用键名访问 current = current.at(key); } } std::cout << "Value of element: " << current.dump() << std::endl; } catch (json::out_of_range& e) { std::cout << "Error: Invalid access path." << std::endl; } catch (std::exception& e) { std::cout << "Error: " << e.what() << std::endl; } return 0; }
代码说明
split_path函数:将输入的路径字符串按.分割成多个节点,方便逐个处理parse_node函数:用正则表达式识别数组格式的节点(比如array[2]),提取出数组名和索引;普通对象键则直接返回- 主逻辑中:从根JSON对象开始,逐个处理每个节点,根据节点类型选择用键名或索引访问,最终得到目标嵌套元素
现在测试时,输入object.array[2].field这种格式的路径,就能正确获取到对应的值了。
内容的提问来源于stack exchange,提问作者Plateau
相关产品推荐
相关产品推荐

