Search code examples
c++jsonnlohmann-json

C++ json insert into array


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.


Solution

  • 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
    ]