C++?JSON庫?nlohmann::basic_json::array?的用法示例詳解
簡介
nlohmann::json 是一個 C++ 的 JSON 庫,它提供了一種容易和直觀的方法來處理 JSON 數(shù)據(jù)。nlohmann::json::array()
是用來創(chuàng)建一個 JSON 數(shù)組的方法。
下面是一些基本的例子:
創(chuàng)建一個空的 JSON 數(shù)組:
nlohmann::json j = nlohmann::json::array();
創(chuàng)建一個包含一些元素的 JSON 數(shù)組:
nlohmann::json j = nlohmann::json::array({ "element1", "element2", 3.14, false });
你也可以使用 push_back 或者 emplace_back 方法來向 JSON 數(shù)組添加元素:
nlohmann::json j = nlohmann::json::array(); j.push_back("element1"); j.emplace_back("element2");
遍歷 JSON 數(shù)組的元素:
nlohmann::json j = nlohmann::json::array({ "element1", "element2", 3.14, false }); for (auto& element : j) { std::cout << element << '\n'; }
以上都是 JSON 數(shù)組的基礎(chǔ)用法,實際使用時可以根據(jù)需要進(jìn)行擴(kuò)展和修改。
nlohmann::basic_json::array 官網(wǎng)介紹
static basic_json array(initializer_list_t init = {});
從給定的初始化列表創(chuàng)建一個 JSON 數(shù)組值。也就是說,給定一個值列表 a, b, c
,創(chuàng)建 JSON 值 [a, b, c]
。如果初始化列表為空,則創(chuàng)建空數(shù)組 []
。
參數(shù)
init
(輸入):用于創(chuàng)建數(shù)組的 JSON 值的初始化列表(可選)
返回值
JSON 數(shù)組值
異常安全性
強(qiáng)保證:如果拋出異常,則 JSON 值不會有任何改變。
復(fù)雜度
線性于 init
的大小。
注意
此函數(shù)只需要用來表示兩個無法通過初始化列表構(gòu)造函數(shù)(basic_json(initializer_list_t, bool, value_t)
)實現(xiàn)的邊緣情況。這些情況是:
- 創(chuàng)建一個所有元素都是第一個元素為字符串的對的數(shù)組 - 在這種情況下,初始化列表構(gòu)造函數(shù)會創(chuàng)建一個對象,將第一個元素作為鍵
- 創(chuàng)建一個空數(shù)組 - 將空的初始化列表傳遞給初始化列表構(gòu)造函數(shù)會生成一個空對象
示例
以下代碼展示了 array
函數(shù)的示例。
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // 創(chuàng)建 JSON 數(shù)組 json j_no_init_list = json::array(); json j_empty_init_list = json::array({}); json j_nonempty_init_list = json::array({1, 2, 3, 4}); json j_list_of_pairs = json::array({ {"one", 1}, {"two", 2} }); // 序列化 JSON 數(shù)組 std::cout << j_no_init_list << '\n'; std::cout << j_empty_init_list << '\n'; std::cout << j_nonempty_init_list << '\n'; std::cout << j_list_of_pairs << '\n'; }
輸出:
[]
[]
[1,2,3,4]
[["one",1],["two",2]]
另請參閱
basic_json(initializer_list_t)
- 從初始化列表創(chuàng)建一個 JSON 值object
- 從初始化列表創(chuàng)建一個 JSON 對象值
版本歷史
在版本 1.0.0 中添加。
到此這篇關(guān)于C++ JSON庫 nlohmann::basic_json::array 的用法的文章就介紹到這了,更多相關(guān)C++ nlohmann::basic_json::array內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Visual?C++?6.0添加一個對話框的實現(xiàn)步驟
VC6.0是微軟公司推出的一款集成開發(fā)環(huán)境,本文主要介紹了Visual?C++?6.0添加一個對話框的實現(xiàn)步驟,具有一定的參考價值,感興趣的可以了解一下2024-06-06c++文件監(jiān)控之FileSystemWatcher
為了監(jiān)控web程序的靜態(tài)文件是否被惡意改動,所以學(xué)習(xí)了一下FileSystemWatcher 類對文件的監(jiān)控,由于還在初級階段,這里只貼一下關(guān)于FileSystemWatcher學(xué)習(xí)的一些代碼2019-04-04基于VC中使用ForceInclude來強(qiáng)制包含stdafx.h的解決方法
本篇文章是對VC中使用ForceInclude來強(qiáng)制包含stdafx.h的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05探索Visual C++下創(chuàng)建WPF項目的方法示例
這篇文章主要介紹了探索Visual C++下創(chuàng)建WPF項目的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07