Reputation: 113
I created json objects using nlohmann library with this code:
nlohmann::json dataJson;
auto data = dataJson.array();
data[0]["message"] = "String";
data[0]["timestamp"] = 123;
The output is
{"message":"String", "timestamp": 123}
but i want the output to be
[{"message":"String", "timestamp": 123}]
in an array in order to have the ability to have multiple messages.
So i want to ask what is the best way to add the values in the array, because when I print it, the ouput of the array is null.
I am new at cpp so I want to apologize for the question if is considered too easy, but any help would be appreciated.
Upvotes: 1
Views: 4246
Reputation: 69912
nlohmann_json is a very useful library but it does have a few quirks. I find it's best to be explicit about intent.
Lambdas can be very useful here:
#include <iostream>
#include <nlohmann/json.hpp>
int main() {
auto make_object = []
{
auto result = nlohmann::json::object();
result["message"] = "String";
result["timestamp"] = 123;
return result;
};
auto make_array = [&make_object]
{
auto result = nlohmann::json::array();
result.push_back(make_object());
return result;
};
auto data = make_array();
std::cout << data.dump() << std::endl;
return 0;
}
expected output:
[{"message":"String","timestamp":123}]
Upvotes: 4