C++ Hjson-cpp處理JSON類型配置文件詳解
Hjson-Cpp簡介
Hjson-Cpp是C++實現(xiàn)的Hjson解析庫。Hjson(Human JSON)是JSON的擴展格式,支持注釋、多行字符串等更友好的語法,適用于配置文件等場景。Hjson-Cpp提供將Hjson轉換為JSON或直接解析為C++對象的功能。
- 支持注釋:單行(//)和多行(/* */)注釋
- 寬松語法:字符串可以不加引號,末尾逗號可省略
- 多行字符串:更自然的文本塊表示
- 更友好的錯誤提示:定位配置錯誤更直觀
核心特性
支持標準Hjson語法,包括注釋(#或//)、無引號鍵名、多行字符串。
提供與JSON互轉的能力,兼容現(xiàn)有JSON工具鏈。
輕量級實現(xiàn),僅依賴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 // 帶單位的數(shù)值
}
)";
Hjson::Value config;
try {
config = Hjson::Unmarshal(configStr);
// 訪問數(shù)據(jù)
std::cout << "App: " << config["appName"].to_string() << "\n";
std::cout << "Version: " << config["version"].to_double() << "\n";
// 遍歷數(shù)組
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]:訪問對象成員或數(shù)組元素。
與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";
}
性能建議
對于大型文件,優(yōu)先使用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是數(shù)組類型\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. 自定義解析規(guī)則
// 解析帶單位的數(shù)值
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內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
c語言中單引號和雙引號的區(qū)別(順利解決從字符串中提取IP地址的困惑)
c語言中的單引號和雙引號可是有很大區(qū)別的,使用之前一定要了解他們之間到底有什么不同,下面小編就給大家詳細的介紹一下吧,對此還不是很了解的朋友可以過來參考下2013-07-07
vscode配置遠程開發(fā)環(huán)境并遠程調試運行C++代碼的教程
這篇文章主要介紹了vscode配置遠程開發(fā)環(huán)境并遠程調試運行C++代碼的教程,本文通過截圖實例相結合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04

