2021-07-21 關(guān)于Json文件的讀寫(xiě)

JSON 是一種輕量級(jí)的數(shù)據(jù)交換格式, 格式簡(jiǎn)潔清晰,易于人閱讀和編寫(xiě),也易于機(jī)器的解析和生成。目前Json成為了主流數(shù)據(jù)存儲(chǔ)和交換格式。

JSON in python

python 自帶json module, 可以很好的完成相關(guān)操作。

用python讀取json 文件

import json
with open("data.json", encoding = "utf-8") as f:
    config = json.load(f)

有時(shí)候遇到的parse問(wèn)題一般是encoding沒(méi)有設(shè)置好。

用python寫(xiě)入json 文件

import json
with open("output.json", "w") as f:
     json.dump(config, f, indent = 4)

indent 是為了output美觀,易于人閱讀。

JSON in C++

nlohmann/json.hpp 一個(gè)非常棒的庫(kù)
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();
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容