JSON 是一種輕量級的數(shù)據(jù)交換格式, 格式簡潔清晰,易于人閱讀和編寫,也易于機器的解析和生成。目前Json成為了主流數(shù)據(jù)存儲和交換格式。
JSON in python
python 自帶json module, 可以很好的完成相關操作。
用python讀取json 文件
import json
with open("data.json", encoding = "utf-8") as f:
config = json.load(f)
有時候遇到的parse問題一般是encoding沒有設置好。
用python寫入json 文件
import json
with open("output.json", "w") as f:
json.dump(config, f, indent = 4)
indent 是為了output美觀,易于人閱讀。
JSON in C++
nlohmann/json.hpp 一個非常棒的庫
https://github.com/nlohmann/json
#include <nlohmann/json.hpp>
std::ifstream f;
f.open(config_file.c_str());
// if file does not exists, assert false
if (!f.is_open())
{
KT_CRITICAL("strategy config file {} does not exist", config_file);
assert(false);
}
json strat_config = json::parse(f);
f.close();