How to load JSON from file with jsoncpp?

I'm making the switch from boost::json to jsoncpp, but I am having trouble utilizing jsoncpp to load JSON objects from a .json file. Namely, I do not know how to parse the json file so that its members can be accessed. Here is what I am doing currently:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Json::Value root;
Json::Reader reader;

std::ifstream file("level_objects/entities.json");
file >> root;

if(!reader.parse(file, root, true)){
        //for some reason it always fails to parse
	std::cout  << "Failed to parse configuration\n"
               << reader.getFormattedErrorMessages();
}
//set to 30 in file, but constantly returns 0
int width = root["jumper.width"].asInt();
//equivalent code, also returns 0
width = root.get("jumper.width", 30).asInt();

The output reads:
Failed to parse configuration
* Line 1, Column 1
Syntax error: value, object or array expected.

But that can't be right because I know the file is in valid JSON format. I was using the exact same json file with Boost, but Boost was giving me compile times of around a minute (versus 5 seconds with jsoncpp).

tl;dr:
Can anybody give me a working example (or correct my code) to save me from the headache of learning jsoncpp's usage when loading from a file?
Last edited on
This
1
2
std::ifstream file("level_objects/entities.json");
file >> root;
should read the entire file.
This
1
2
 std::ifstream file("level_objects/entities.json");
file >> root;

should read the entire file.


What exactly do you mean? I expect it to read the whole file, but I don't understand how to use jsoncpp's API in order to access the elements of this file.

Here is the file: multiple online formatters say that this is valid JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
	"jumper": {
		"maxHorizontalVelocity": 5,
		"jumpVelocity": 6,
		"damageVal": 10,
		"width": 30,
		"height": 100
	},
	"melee enemy": {
		"maxHorizontalVelocity": 10,
		"jumpVelocity": 4,
		"damageVal": 3,
		"width": 30,
		"height": 100
	}
}
Last edited on
1
2
3
int w1 = root["jumper"]["width"].asInt();
//or
int w2 = root["jumper"].get("width", 3).asInt();
Last edited on
So jsoncpp doesn't support JSON paths with dots between each level, like what I had before? That just seems annoying. Thanks.
Topic archived. No new replies allowed.