How to use a JSON parser to read and handle data from a .json file?

I've included jsoncpp ( https://github.com/open-source-parsers/jsoncpp ) in my project, but I have a couple of questions. One, do I have to build the project? The documentation on the link mentions using CMake for something, but I've never really used CMake before so I'm not sure if that is necessary. Two, how do I actually use a json library to read a .json file? Like what would the code look like in c++? I'm having trouble really finding any documentation or examples on this, so any links would be appreciated.

I'm using the JSON format to handle game data, like so (code taken from this tutorial: http://gameprogrammingpatterns.com/prototype.html#prototypes-for-data-modeling )
1
2
3
4
5
6
7
{
  "name": "goblin grunt",
  "minHealth": 20,
  "maxHealth": 30,
  "resists": ["cold", "poison"],
  "weaknesses": ["fire", "light"]
}


So in my Goblin class for instance, I'll parse the .json until I find the maxHealth value for Goblin, then use that as necessary in the program. How would I go about doing this?
Last edited on
You can use the boost property tree to read the data:

http://www.boost.org/doc/libs/1_58_0/doc/html/property_tree/reference.html#header.boost.property_tree.json_parser_hpp

CMake is used to generate the project files.
Thanks but I'm still having trouble actually reading and using the data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// example.cpp : Defines the entry point for the console application.
//

#include "boost\property_tree\json_parser.hpp"
#include "boost\foreach.hpp"

int main(){
	int test = 0;

	boost::property_tree::ptree pt;
	boost::property_tree::read_json("files/test.json", pt);
	
	BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt){
		test = v.second;
	}

	return 0;
}


And test.json
1
2
3
{
    "number" : 10
}


So I want to set test to 10, via the data in the .json file. But in the line test = v.second; v is underlined saying that there is no conversion between a
boost::property_tree::basic_ptree<std::string, std::string, std::less<std::string>> to int
. What would be the correct syntax for reading the data of a .json and setting a variable to that data?
Last edited on
Wait now I got it. I'm not sure why the OP on stack overflow was using that foreach function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "boost\property_tree\json_parser.hpp"
#include "boost\foreach.hpp"
#include <iostream>

int main(){
	int test = 0;
	std::cout << test << "\n";

	boost::property_tree::ptree pt;
	boost::property_tree::read_json("files/test.json", pt);

	test = pt.get<int>("number");

	std::cout << test;

	return 0;
}
Topic archived. No new replies allowed.