-1

I am using nlohmann json. I want to insert into an array. I know in javascript there is a Array.prototype.splice that allows you to insert into an array. Is there a similar way in nlohmann's json.

I want this to happen:

//from this:
[1, 2, 3, 5]

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

Basically I want something similar to the std::vector insert method.

Ank i zle
  • 2,089
  • 3
  • 14
  • 36
  • Welcome to Stack Overflow. Can you show in the question a [mre] which includes what you have already tried (as code), the error, the input, and the expected output? Thanks. – L. F. Feb 23 '20 at 02:19

1 Answers1

2

The following example should work, assuming you're using the single-include json.hpp and it's in the set of include directories used by your compiler. Otherwise, modify the #include as needed.:

#include "json.hpp"                                      
#include <iostream>                                      

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

This should print:

[
  0,
  1,
  2
]

[
  0,
  "foo",
  1,
  2
]
druckermanly
  • 2,694
  • 15
  • 27