当前位置: 代码网 > it编程>编程语言>Javascript > C++ Hjson-cpp处理JSON类型配置文件详解

C++ Hjson-cpp处理JSON类型配置文件详解

2025年06月17日 Javascript 我要评论
hjson-cpp简介hjson-cpp是c++实现的hjson解析库。hjson(human json)是json的扩展格式,支持注释、多行字符串等更友好的语法,适用于配置文件等场景。hjson-c

hjson-cpp简介

hjson-cpp是c++实现的hjson解析库。hjson(human json)是json的扩展格式,支持注释、多行字符串等更友好的语法,适用于配置文件等场景。hjson-cpp提供将hjson转换为json或直接解析为c++对象的功能。

  • 支持注释:单行(//)和多行(/* */)注释
  • 宽松语法:字符串可以不加引号,末尾逗号可省略
  • 多行字符串:更自然的文本块表示
  • 更友好的错误提示:定位配置错误更直观

核心特性

支持标准hjson语法,包括注释(#或//)、无引号键名、多行字符串。

提供与json互转的能力,兼容现有json工具链。

轻量级实现,仅依赖c++11标准库。

安装与集成

使用cmake集成hjson-cpp:

find_package(hjsoncpp required)
target_link_libraries(your_target private hjsoncpp)

或手动下载源码后,将include/hjson目录添加到项目头文件路径。

基本用法示例

解析hjson字符串并读取内容:

#include <hjson/hjson.h>
#include <iostream>
#include <fstream>

int main() {
    // 从字符串解析
    std::string configstr = r"(
        // 这是一个hjson配置示例
        {
            appname: my application  // 字符串可以不加引号
            version: 1.2.3
            features: [
                "fast-mode"  // 引号也是允许的
                dark-theme   // 这种写法也可以
                auto-save    // 最后一个元素可以不加逗号
            ]
            /* 多行
               注释 */
            timeout: 30s  // 带单位的数值
        }
    )";

    hjson::value config;
    try {
        config = hjson::unmarshal(configstr);
        
        // 访问数据
        std::cout << "app: " << config["appname"].to_string() << "\n";
        std::cout << "version: " << config["version"].to_double() << "\n";
        
        // 遍历数组
        std::cout << "features:\n";
        for (auto& feature : config["features"]) {
            std::cout << " - " << feature.to_string() << "\n";
        }
    } catch (hjson::syntax_error& e) {
        std::cerr << "配置语法错误: " << e.what() << "\n";
        return1;
    }

    return0;
}

常用api说明

hjson::marshal(value):将c++对象序列化为hjson字符串。

hjson::unmarshal(text):解析hjson文本为hjson::value对象。

value.to_string()/to_int():类型转换方法。

value[key]:访问对象成员或数组元素。

与json互转

将json转为hjson(保留注释等扩展特性):

hjson::value jsondata = hjson::unmarshal(jsontext);
std::string hjsontext = hjson::marshal(jsondata);

错误处理

解析失败时抛出hjson::syntax_error异常:

try {
    hjson::unmarshal("invalid hjson");
} catch (const hjson::syntax_error& e) {
    std::cerr << "error: " << e.what() << "\n";
}

性能建议

对于大型文件,优先使用unmarshalfromfile直接读取文件。

频繁操作时可复用hjson::value对象减少内存分配。

高级特性

1. 类型安全访问

// 安全获取配置值(带默认值)
std::string appname = config.get("appname", "default app");
int timeout = config.get("timeout", 10);  // 自动类型转换

// 检查类型
if (config["features"].type() == hjson::type::vector) {
    std::cout << "features是数组类型\n";
}

// 类型转换方法
double version = config["version"].to_double();
std::string versionstr = config["version"].to_string();  // 自动转换

2. 文件操作

// 从文件加载配置
try {
    hjson::value fileconfig = hjson::unmarshalfromfile("config.hjson");
    
    // 修改配置
    fileconfig["lastrun"] = hjson::value(time(nullptr));
    
    // 写回文件(保留注释和格式)
    hjson::marshaltofile(fileconfig, "config.hjson");
} catch (hjson::file_error& e) {
    std::cerr << "文件操作失败: " << e.what() << "\n";
}

3. 自定义解析规则

// 解析带单位的数值
hjson::decoderoptions options;
options.unitresolver = [](const std::string& unit, double value) {
    if (unit == "s") return value * 1000;  // 秒转毫秒
    if (unit == "min") return value * 60 * 1000;
    return value;
};

hjson::value customconfig = hjson::unmarshal("timeout: 30s", options);
std::cout << "timeout in ms: " << customconfig["timeout"].to_int64() << "\n";

使用教程

下载

点击https://github.com/hjson/hjson-cpp跳转到github:

点击download下载源码。

使用

vs新建工程:

拷贝hjson源码进入工程目录:

编写测试代码:

#include <iostream>
#include "hjson.h"

using namespace std;


static const char* _szdefaultconfig = r"(
{
  imagesource: no default
  showimages: true
  writeimages: true
  printframeindex: false
  printframerate: true
}
)";


hjson::value getconfig(const char* szconfigpath) {
    hjson::value defaultconfig = hjson::unmarshal(_szdefaultconfig);

    hjson::value inputconfig;
    try {
        inputconfig = hjson::unmarshalfromfile(szconfigpath);
    }
    catch (const std::exception& e) {
        std::fprintf(stderr, "error in config: %s\n\n", e.what());
        std::fprintf(stdout, "default config:\n");
        std::fprintf(stdout, _szdefaultconfig);

        return hjson::value();
    }

    return hjson::merge(defaultconfig, inputconfig);
}

int main()
{
    string path = "c:\\users\\徐鹏\\desktop\\hjson\\test.json";
    hjson::value val = getconfig(path.c_str());
    printf("%s\r\n",val["imagesource"].to_string().c_str());
    hjson::value a = val.at("showimages");
    printf("%d\r\n", a.to_int64());
	return 0;
}

运行查看结果:

到此这篇关于c++ hjson-cpp处理json类型配置文件详解的文章就介绍到这了,更多相关c++处理json内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com