应使用具备完整解析能力的库进行实际解析并捕获异常,如nlohmann/json(try-catch)、RapidJSON(SAX模式)、Boost.PropertyTree(间接校验)或cJSON(返回值判断)。

如果您需要在 C++ 程序中验证一段字符串是否符合 JSON 语法规范,仅靠手动匹配括号或正则表达式无法覆盖 JSON 的完整语义规则,必须借助具备完整解析能力的库进行实际解析并捕获异常。以下是几种主流且可靠的校验方法:
一、使用 nlohmann/json 库进行 try-catch 解析
nlohmann/json 是头文件级轻量库,支持直接从 std::string 构造 json 对象,若字符串非法则抛出 nlohmann::json::parse_error 异常,适合快速嵌入和单次校验。
1、包含头文件:#include
2、声明命名空间别名:using json = nlohmann::json;
3、将待校验字符串传入 json::parse() 并捕获异常:try { json::parse(input_str); return true; } catch (const json::parse_error&) { return false; }
二、使用 RapidJSON 的 Reader 配合 BaseReaderHandler
RapidJSON 采用 SAX 模式解析,不构建完整 DOM 树,内存占用低且解析速度快;通过自定义 handler 并启用 strict mode,可在发现语法错误时立即终止并返回 false。
1、定义空操作 handler 类继承自 rapidjson::BaseReaderHandler<:utf8>, YourHandler>
2、创建 rapidjson::Reader 实例,并调用 Parse(input_str.c_str(), handler)
3、检查返回值:reader.Parse(...) == true 表示有效,否则为无效 JSON
三、使用 Boost.PropertyTree 进行间接校验
Boost.PropertyTree 并非专为 JSON 设计,但其 read_json() 函数在解析失败时会抛出 boost::property_tree::json_parser::json_parser_error 异常,可作为备用校验路径,适用于已集成 Boost 的项目。
1、包含头文件:#include
2、声明 property_tree 变量:boost::property_tree::ptree pt;
3、调用解析函数并捕获异常:try { std::istringstream is(input_str); read_json(is, pt); return true; } catch (const boost::property_tree::json_parser::json_parser_error&) { return false; }
四、使用 cJSON 的 cJSON_Parse() 返回值判断
cJSON 是纯 C 编写的轻量解析器,C++ 中可直接链接使用;cJSON_Parse() 在输入非法时返回 nullptr,合法时返回根节点指针,需注意后续调用 cJSON_Delete() 释放内存。
1、包含头文件:#include "cjson/cJSON.h"
2、调用解析函数:cJSON* root = cJSON_Parse(input_str.c_str());
3、判断返回值并清理:if (root) { cJSON_Delete(root); return true; } else { return false; }
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











