// 极简 JSON **只读**解析(零外部依赖)—— 只为"现场用配置文件改参数,不重编译"服务。 // // 为什么不引第三方库(nlohmann/json 等): // * 交付形态要求核心零外部依赖(cpp/README.md §1):一个第三方头就会把这条打破, // 而现场只需要"读 configs/*.json 里的标量 / 数组 / 字符串"; // * 自实现才能保证**确定性**(无随机、无 locale 依赖、无异常抛出), // 便于自检与现场排错(现场最怕"一个字母打错,整机起不来却看不出哪里错")。 // // 与 Python 侧的一致性(避免同一个文件两种解释): // * 语法按 RFC 8259 **严格**解析(与 Python `json` 模块同口径):不支持注释、不支持尾逗号、 // 字符串必须双引号、数字不接受前导 `+` 与 `01`; // * `\uXXXX` 按 UTF-8 输出(含代理对)→ 配置里写中文 `_note` 能原样保留; // * 重复键:后值覆盖前值(与 Python 一致); // * 解析失败返回**带行列号的错误文本**(不抛异常),调用点原样打印即可定位。 #pragma once #include #include #include #include namespace portcv { namespace json { /// JSON 值类型。 enum class Type { Null, Bool, Number, String, Array, Object }; /// 只读 JSON 值。配置文件都很小,拷贝成本可忽略,因此直接用值语义(不搞 share_ptr)。 struct Value { Type type = Type::Null; bool boolean = false; ///< type == Bool 时有意义 double number = 0.0; ///< type == Number 时有意义 /// type == Number 时的**原始字面量**(如 "180" / "180.0" / "1e+16")。 /// 为什么保留:Python `json` 区分 int/float(`dumps(180)`→"180",`dumps(180.0)`→"180.0"), /// 只留 double 就把这个区别丢了 —— 标定记录的 sha256 会因此与 Python 不一致。 std::string raw; std::string text; ///< type == String 时有意义 std::vector items; ///< type == Array std::vector> members; ///< type == Object(保留书写顺序) bool is_null() const { return type == Type::Null; } bool is_bool() const { return type == Type::Bool; } bool is_number() const { return type == Type::Number; } bool is_string() const { return type == Type::String; } bool is_array() const { return type == Type::Array; } bool is_object() const { return type == Type::Object; } /// 数组元素数 / 对象成员数;其它类型返回 0(字符串长度请直接看 `text.size()`)。 std::size_t size() const; /// 取对象成员;不存在返回 Null 静态空值(可直接 `.is_number()` 判空)。 const Value& member(const std::string& key) const; /// 取数组元素;越界返回 Null。 const Value& item(std::size_t index) const; /// 是否含某成员。 bool has(const std::string& key) const; /// 对象成员名(按书写顺序)。 std::vector keys() const; /// 类型名("null"/"bool"/"number"/"string"/"array"/"object",错误信息与日志用)。 const char* type_name() const; }; /// 解析 JSON 文本;失败返回 Null 并填写 `error`(含 1 基行列号)。 Value parse(const std::string& text, std::string* error); /// 读文件并解析(UTF-8;容忍开头 BOM —— 现场用记事本另存常带 BOM, /// 而 BOM 不是内容,丢掉不影响语义)。失败时填写 `error`。 Value parse_file(const std::string& path, std::string* error); /// 读整个文本文件(二进制读,不做换行转换;UTF-8 BOM 会被去掉)。 bool read_file(const std::string& path, std::string* out, std::string* error); } // namespace json } // namespace portcv