Visual Studio
C++ boost를 이용한 json 데이터 파싱(parsing)
내맴이여
2024. 5. 21. 22:36
반응형
1. 시험환경
· 윈도우
· C++
· boost
2. 목적
· C++ Boost 라이브러리를 이용하여 json 파일을 읽어서 파싱(parsing)하는 예제 코드를 작성한다.
3. 적용
① json 샘플 데이터
- 파일명 : Config.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
{
"encoding":"UTF-8",
"config_type":"dev",
"port":8899,
"log":
{
"max_size":1024,
"write_file":true,
"print_screen":true
},
"database":
[
{
"desc":"no.1",
"address":"127.0.0.1",
"port":4443,
"instance":"test_instance1",
"id":"sa",
"password":"asdf1234$"
},
{
"desc":"no.2",
"address":"127.0.0.1",
"port":5443,
"instance":"test_instance2",
"id":"sa",
"password":"asdf1234$"
}
]
}
|
cs |
② json 형식의 데이터를 파싱하는 코드이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
int main()
{
try
{
using boost::property_tree::ptree;
using std::string;
ptree props;
boost::property_tree::read_json("Config.json", props);
string encoding = props.get<string>("encoding");
std::cout << "Encoding=" << encoding << std::endl;
string config_type = props.get<string>("config_type");
std::cout << "config_type=" << config_type << std::endl;
unsigned short port = props.get<unsigned short>("port");
std::cout << "port=" << port << std::endl;
std::cout << "[Log]" << std::endl;
ptree &log_child = props.get_child("log");
int size = log_child.get<int>("max_size");
std::cout << "size=" << size << std::endl;
bool write_file = log_child.get<bool>("write_file");
std::cout << "write_file=" << std::boolalpha << write_file << std::endl;
std::cout.setf(std::ios::boolalpha);
bool print_screen = log_child.get<bool>("print_screen");
std::cout << "print_screen=" << print_screen << std::endl;
std::cout << "[Database]" << std::endl;
ptree &db_child = props.get_child("database");
// array!
int idx = 0;
BOOST_FOREACH(ptree::value_type &vt, db_child)
{
string desc = vt.second.get<string>("desc");
string address = vt.second.get<string>("address");
unsigned short port = vt.second.get<unsigned short>("port");
string instance = vt.second.get<string>("instance");
string id = vt.second.get<string>("id");
string password = vt.second.get<string>("password");
std::cout << idx++ << " " << desc << " " << address << " " << port << " " << instance << " " << id << " " << password << std::endl;
}
}
catch (std::exception& e)
{
std::cout << e.what();
}
return 0;
}
|
cs |
반응형