从json文件中取任意key对应的value值

#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;
}
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值