How to add an Object to an Array? #2985
-
Hello, I have a question. how can I add an object to an array? [] I want to make it to this: [
{"label": "key", "value": "var"},
{"label": "string", "value": "hello world"}
] But how can I do it? res.push_back({json::object({"label", "key", "value", "var"})});
res.push_back({json::object({"label", "string", "value", "hello world"})}); But it just give me error: |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The For your example: res.push_back(json::object({{"label", "key"}, {"value", "var"}}));
res.push_back(json::object({{"label", "string"}, {"value", "hello world"}})); You can also skip the res.push_back({{"label", "key"}, {"value", "var"}});
res.push_back({{"label", "string"}, {"value", "hello world"}}); |
Beta Was this translation helpful? Give feedback.
The
object
function expects a list of pairs (see https://json.nlohmann.me/api/basic_json/object/). You could also use the second version ofpush_back
and provide an object value directly (see https://json.nlohmann.me/api/basic_json/push_back/).For your example:
You can also skip the
json::object
here, because list of pairs are treated as object anyway: