Json: Adding JSON Array to the Array

Created on 24 Aug 2018  路  2Comments  路  Source: nlohmann/json

can we have a function , which allows us to add a json array of elements to the another instance of json array at the end.
I guess this feature is not available. please ignore if this is already exits and kindly let me know the function or method name. I have gone through the documentation and not found anything.

ex: json first = json::parse("[{\"name\":\"John\",\"gender\":"male"},{\"name\":\"Ben\",\"gender\":"female"}]");

json second = json::parse("[{\"name\":\"Poole\",\"gender\":"male"},{\"name\":\"Neil\",\"gender\":"female"}]");
// Appending second array of elements to the first json array object 
first.append(second);

question proposed fix

Most helpful comment

The JSON library uses std::vector internally and uses nearly the same API. So taking the answer from https://stackoverflow.com/questions/2551775/appending-a-vector-to-a-vector:

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

using json = nlohmann::json;

int main(int argc, const char **argv) {
    json a = {1,2,3};
    json b = {4,5,6};

    a.insert(a.end(), b.begin(), b.end());

    std::cout << a << std::endl;
}

All 2 comments

The JSON library uses std::vector internally and uses nearly the same API. So taking the answer from https://stackoverflow.com/questions/2551775/appending-a-vector-to-a-vector:

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

using json = nlohmann::json;

int main(int argc, const char **argv) {
    json a = {1,2,3};
    json b = {4,5,6};

    a.insert(a.end(), b.begin(), b.end());

    std::cout << a << std::endl;
}

Wow..Thank you.

Was this page helpful?
0 / 5 - 0 ratings