' what(): [json.exception.type_error.305] cannot use operator[] with a string ar...

2026年03月02日 20:39 状态: processing

🚨 错误信息

terminate called after throwing an instance of 'nlohmann::json_abi_v3_11_3::detail::type_error' what(): [json.exception.type_error.305] cannot use operator[] with a string argument with array

🤖 AI解决方案

报错分析报告

1. 错误翻译



原文:[json.exception.type_error.305] cannot use operator[] with a string argument with array
译文:[json.exception.type_error.305] 无法对数组使用带字符串参数的operator[]运算符

2. 原因分析


  • 根本原因:尝试用字符串键operator[]的字符串参数)访问JSON数组(数组需用整数索引)。

  • 发生位置:代码中调用nlohmann::json对象的operator[]时,传入字符串参数但该对象实际是数组类型。
  • 3. 解决方案


    cpp
    #include
    using json = nlohmann::json;

    // 修复后的代码示例:区分数组与对象的访问方式
    void safe_access(json data) {
    if (data.is_array()) {
    // 数组→用整数索引
    int elem = data[0]; // 正确访问第一个元素
    } else if (data.is_object()) {
    // 对象→用字符串键
    int value = data["key"]; // 正确访问键值
    }
    }

    // 反例修正(原错误场景)
    void fix_example() {
    json arr = json::parse("[10,20,30]");
    // 错误:arr是数组,不能用字符串索引 → 改为整数索引
    int correct_val = arr[1]; // 取第二个元素(值为20)
    }

    4.️ 预防措施


  • 类型检查优先:访问前用is_array()/is_object()验证JSON值类型,避免类型误用。

  • 工具辅助:用clang-tidy(C++静态分析)或VSCode的JSON Tools插件实时检测类型不匹配。

  • ---
    若有其他报错,请直接粘贴错误信息。