2021-07-21 关于Json文件的读写

JSON 是一种轻量级的数据交换格式, 格式简洁清晰,易于人阅读和编写,也易于机器的解析和生成。目前Json成为了主流数据存储和交换格式。

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();
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容