14. JSON
1. jsoncpp
설치 - Python
2. JSON 파일 쓰기
#include <fstream>
#include <iostream>
#include <string>
#include "json/json.h"
using namespace std;
using namespace Json;
int main() {
ofstream json_file;
json_file.open("json_exam.json");
Value main;
main["Job1"] = "developer";
main["Job2"] = "author";
Value sub;
sub["Sub1"] = "Sub1";
sub["Sub2"] = "Sub2";
main["SubItems"] = sub;
main["Sub3"] = "blogger";
StyledWriter writer;
string str = writer.write(main);
cout << str << endl
<< endl;
json_file << writer.write(main);
json_file.close();
return 0;
}
3. JSON 파일 읽기
#include <fstream>
#include <iostream>
#include <string>
#include "json/json.h"
using namespace std;
using namespace Json;
int main() {
ifstream json_dir("json_exam.json");
Reader reader;
Value value;
bool is_parse = reader.parse(json_dir, value);
if (is_parse == true) {
cout << "Job1: " << value["Job1"] << endl;
cout << "SubItems Sub1: " << value["SubItems"]["Sub1"] << endl;
} else {
cout << "JSON 파일을 읽을 수 없습니다." << endl;
}
return 0;
}
4. JSON 배열 사용
#include <fstream>
#include <iostream>
#include <string>
#include "json/json.h"
using namespace std;
using namespace Json;
int main() {
ofstream json_write;
json_write.open("json_exam.json");
Value root;
root["Title"] = "Array Exam";
Value array1;
array1.append("C#");
array1.append("C++");
Value array2;
array2.append("Q#");
array2.append("Qt");
root["Language"]["Sample1"] = array1;
root["Language"]["Sample2"] = array2;
json_write << root;
json_write.close();
ifstream json_open("json_exam.json");
Reader reader;
Value value;
reader.parse(json_open, value);
cout << value << endl
<< endl;
for (auto i : value["Language"]["Sample1"])
cout << "Language Sample1: " << i << endl;
return 0;
}
5. JSON 타입 선택 읽기
#include <fstream>
#include <iostream>
#include <string>
#include "json/json.h"
using namespace std;
using namespace Json;
int main() {
ofstream json_write;
json_write.open("json_exam.json");
Value root;
root["Title"] = "Convert Exam";
root["IsJson"] = true;
Value numbers;
numbers["No1"] = 12;
numbers["No2"] = 20.3;
root["Array"]["Number"] = numbers;
json_write << root;
json_write.close();
ifstream json_open("json_exam.json");
Reader reader;
Value value;
reader.parse(json_open, value);
cout << value["Array"]["Number"].get("No1", -1).asInt() << endl;
cout << value["Array"]["Number"].get("No2", -1).asDouble() << endl;
cout << value["Array"]["Number"].get("No1", "Empty").asString() << endl;
cout << boolalpha << value.get("IsJson", false).asBool() << endl;
return 0;
}
6. JSON 요소 크기 확인
#include <fstream>
#include <iostream>
#include <string>
#include "json/json.h"
using namespace std;
using namespace Json;
int main() {
ifstream json_open("json_exam.json");
Reader reader;
Value value;
reader.parse(json_open, value);
cout << "Root 크기: " << value.size() << endl;
cout << "Array 크기: " << value["Array"].size() << endl;
cout << "Number 크기: " << value["Array"]["Number"].size() << endl;
return 0;
}