#include <nlohmann/json.hpp>
#include <iostream>
#include <string>
#include <typeinfo>
// 递归函数,用于搜索键并获取其值
nlohmann::json::value_type
searchValueByKey(const nlohmann::json& j, const std::string& key)
{
// 如果是对象,尝试查找键
if (j.is_object())
{
for (auto& el : j.items())
{
if (el.key() == key)
{
return el.value(); // 返回找到的值
}
// 如果值还是一个 JSON 对象或数组,递归搜索
else if (el.value().is_object() || el.value().is_array())
{
auto result = searchValueByKey(el.value(), key);
if (!result.is_null())
{ // 如果在子对象中找到了键,返回其值
return result;
}
}
}
}
// 如果没有找到键,返回 null 作为未找到的标记
return nlohmann::json::value_type();
}
int
main()
{
// 给定的 JSON 数据
nlohmann::json j = R"({
"shcool": {
"stduent": {
"kangkang": {
"name": "John",
"age": 30
}
}
}
})"_json;
// 搜索 "age" 键的值
auto age_value = searchValueByKey(j, "age");
if (!age_value.is_null())
{
std::cout << "Found age: " << age_value << std::endl;
}
else
{
std::cout << "Age not found." << std::endl;
}
// 搜索 "kangkang" 键的值
auto kangkang_value = searchValueByKey(j, "kangkang");
if (!kangkang_value.is_null())
{
std::cout << "Found kangkang: " << kangkang_value << std::endl;
}
else
{
std::cout << "Kangkang not found." << std::endl;
}
auto mike_value = searchValueByKey(j, "mike");
if (!mike_value.is_null())
{
std::cout << "Found mike: " << mike_value << std::endl;
}
else
{
std::cout << "mike not found." << std::endl;
}
return 0;
}
从json文件中取任意key对应的value值
最新推荐文章于 2025-03-07 15:15:29 发布