C++json插入数组

C++ json insert into array

本文关键字:数组 插入 C++json      更新时间:2023-10-16

我使用的是nlohmann json。我想插入一个数组。我知道在javascript中有一个Array.prototype.splice,它允许您插入到数组中。在nlohmann的json中有类似的方法吗。

我希望这种情况发生:

//from this:
[1, 2, 3, 5]
//insert at position 3 the value 4
[1, 2, 3, 4, 5]

基本上,我想要类似于std::vector插入方法的东西。

下面的例子应该有效,假设您使用的是单个includejson.hpp,并且它位于编译器使用的include目录集中。否则,根据需要修改#include

#include "json.hpp"                                      
#include <iostream>                                      
int main() {                                             
nlohmann::json json = nlohmann::json::array({0, 1, 2});
std::cout << json.dump(2) << "nn";                     
json.insert(json.begin() + 1, "foo");                  
std::cout << json.dump(2) << 'n';                     
}                

这应该打印:

[
0,
1,
2
]
[
0,
"foo",
1,
2
]