-1

I am unable to insert a JSON object into another object using c++ library “nlohmann json”. An array is inserted instead of an object. I want to get And it turns out

The code I am using: playersSkins.push_back(json::object_t::value_type(playerName, {"color", "#000"}));

Er2n
  • 1
  • 2

1 Answers1

2

Per documentation on nlohmann::json::object(), the initializer list needs to contain pairs for it to be treated as an object. Otherwise it will be treated as an array.

#include <nlohmann/json.hpp>

#include <iostream>

int main()
{
    nlohmann::json playerSkins;
    std::string playerName = "player";
    playerSkins.push_back({{playerName, {{"color", "#000"}}}});;
    std::cout << playerSkins.dump() << "\n";
}

Output:

[{"player":{"color":"#000"}}]

https://godbolt.org/z/n73oKxshe

Kevin
  • 6,993
  • 1
  • 15
  • 24
  • I wanted an object to be created for each player. as I understand it, to create an object, you need double brackets. If so then my code should look like this https://skr.sh/sFfX1wrfdWT. But it doesn't compile – Er2n Aug 29 '22 at 15:50
  • @Er2n You're missing the double brackets around the player name and color object like I have in my example. `push_back` takes a single argument but you're passing two. `playerSkins.push_back({{playerName, {{...}}}});` not `playerSkins.push_back(playerName, {{...}});` – Kevin Aug 29 '22 at 16:41
  • Sorry, I made a mistake in my last post. I wanted to write that I would not like the object to be created for each player. – Er2n Aug 30 '22 at 07:08
  • @Er2n I'm not sure I follow. Do you not want `playerSkins` to be an array? If that's the case then you want to do `playerSkins[playerName] = {{"color", "#000"}};` instead. Calling `playerSkins.push_back` makes `playerSkins` into an array. – Kevin Aug 30 '22 at 17:07