/
Oppq
/
Labs
Обзор
Документация
Войти
/
Oppq
/
Labs
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Lab8/json_test.cpp
373 строки
12 KB
Oppq
Lab8
21 май 2026, 07:41
Верифицирован
21 май 2026, 07:41
2cd3883
Код
Авторство
О чём код?
#include <iostream> #include <fstream> #include <string> #include <vector> #include "json.hpp" #include "json_menu.h" using namespace std; using json = nlohmann::json; void test_create() { int choice; do { showCreateMenu(); cin >> choice; switch(choice) { case 1: { json j; cout << "Пустой JSON: " << j << endl; break; } case 2: { json j = {{"name", "Alice"}, {"age", 25}, {"city", "Moscow"}}; cout << "Объект: " << j.dump(2) << endl; break; } case 3: { json j = {10, 20, 30, 40, 50}; cout << "Массив: " << j.dump() << endl; break; } case 4: { json j = {{"user", {{"name", "Bob"}, {"age", 30}}}, {"scores", {100, 90, 80}}}; cout << "Вложенный объект:\n" << j.dump(2) << endl; break; } case 5: { json j; j["null_val"] = nullptr; j["bool_val"] = true; j["int_val"] = 42; j["float_val"] = 3.14; j["string_val"] = "hello"; j["array_val"] = {1, 2, 3}; j["object_val"] = {{"key", "value"}}; cout << "Разные типы:\n" << j.dump(2) << endl; break; } case 0: break; default: cout << "Неверный выбор" << endl; } } while(choice != 0); } void test_access() { json j = {{"name", "Bob"}, {"age", 30}, {"scores", {95, 87, 92}}, {"address", {{"city", "SPb"}, {"street", "Nevsky"}}}}; cout << "Исходный объект:\n" << j.dump(2) << endl; int choice; do { showAccessMenu(); cin >> choice; switch(choice) { case 1: { cout << "j[\"name\"] = " << j["name"] << endl; cout << "j[\"scores\"][0] = " << j["scores"][0] << endl; break; } case 2: { try { cout << "j.at(\"name\") = " << j.at("name") << endl; cout << "j.at(\"bad\") = " << j.at("bad") << endl; } catch (json::out_of_range& e) { cout << "Ошибка: ключ не найден" << endl; } break; } case 3: { string name = j.value("name", "no name"); string phone = j.value("phone", "no phone"); int age = j.value("age", 0); cout << "name = " << name << endl; cout << "phone = " << phone << endl; cout << "age = " << age << endl; break; } case 4: { cout << "Есть 'name': " << j.contains("name") << endl; cout << "Есть 'phone': " << j.contains("phone") << endl; break; } case 5: { cout << "Размер объекта: " << j.size() << endl; cout << "Размер scores: " << j["scores"].size() << endl; break; } case 6: { json empty; cout << "Объект пуст? " << j.empty() << endl; cout << "Пустой JSON пуст? " << empty.empty() << endl; break; } case 7: { cout << "Все ключи:\n"; for (auto& item : j.items()) { cout << " " << item.key() << " = " << item.value() << endl; } break; } case 0: break; default: cout << "Неверный выбор" << endl; } } while(choice != 0); } void test_modify() { int choice; do { showModifyMenu(); cin >> choice; switch(choice) { case 1: { json j; j["name"] = "Alice"; j["age"] = 25; j["city"] = "Moscow"; cout << "Результат: " << j.dump(2) << endl; break; } case 2: { json j = {1, 2, 3}; j.push_back(4); j.push_back(5); j.push_back(6); cout << "После push_back: " << j.dump() << endl; break; } case 3: { json j = {{"a", 1}, {"b", 2}}; j.emplace("c", 3); j.emplace("d", 4); cout << "После добавления: " << j.dump() << endl; break; } case 4: { json j = {{"a", 1}, {"b", 2}, {"c", 3}, {"d", 4}}; j.erase("b"); j.erase("c"); cout << "После erase: " << j.dump() << endl; break; } case 5: { json j = {{"a", 1}, {"b", 2}, {"c", 3}}; cout << "До clear, размер: " << j.size() << endl; j.clear(); cout << "После clear, размер: " << j.size() << endl; break; } case 6: { json j = {{"name", "Test"}, {"value", 123}, {"active", true}}; cout << "dump() без форматирования: " << j.dump() << endl; cout << "dump(4) с форматированием:\n" << j.dump(4) << endl; break; } case 7: { json j = 123; int val = j.get<int>(); cout << "JSON 123 -> int: " << val << endl; break; } case 8: { json j = "Hello World"; string val = j.get<string>(); cout << "JSON Hello World -> string: " << val << endl; break; } case 0: break; default: cout << "Неверный выбор" << endl; } } while(choice != 0); } void test_file() { int choice; do { showFileMenu(); cin >> choice; switch(choice) { case 1: { json j = {{"name", "MyData"}, {"value", 12345}, {"date", "2025-05-21"}, {"tags", {"json", "cpp", "test"}}}; ofstream file("output.json"); file << j.dump(4); file.close(); cout << "Сохранено в output.json" << endl; break; } case 2: { ifstream file("output.json"); if (file.is_open()) { json j; file >> j; cout << "Прочитано из файла:\n" << j.dump(2) << endl; } else { cout << "Файл output.json не найден" << endl; } break; } case 3: { string json_str = R"({"name":"John","age":30,"city":"New York"})"; json j = json::parse(json_str); cout << "Результат парсинга:\n" << j.dump(2) << endl; string bad_json = "{bad json}"; try { json j2 = json::parse(bad_json); } catch (json::parse_error& e) { cout << "Ошибка парсинга: некорректный JSON" << endl; } break; } case 0: break; default: cout << "Неверный выбор" << endl; } } while(choice != 0); } void test_types() { cout << "\n========== ПРОВЕРКА ТИПОВ ==========\n"; json j_null = nullptr; json j_bool = true; json j_number = 123; json j_float = 3.14; json j_string = "hello"; json j_array = {1, 2, 3, 4, 5}; json j_object = {{"key1", "value1"}, {"key2", 42}}; cout << "null.is_null(): " << j_null.is_null() << endl; cout << "123.is_number(): " << j_number.is_number() << endl; cout << "123.is_number_integer(): " << j_number.is_number_integer() << endl; cout << "3.14.is_number_float(): " << j_float.is_number_float() << endl; cout << "hello.is_string(): " << j_string.is_string() << endl; cout << "[1,2,3,4,5].is_array(): " << j_array.is_array() << endl; cout << "объект.is_object(): " << j_object.is_object() << endl; cout << "true.is_boolean(): " << j_bool.is_boolean() << endl; } void test_comparison() { cout << "\n========== ОПЕРАТОРЫ СРАВНЕНИЯ ==========\n"; json j1 = {{"a", 1}, {"b", 2}, {"c", 3}}; json j2 = {{"a", 1}, {"b", 2}, {"c", 3}}; json j3 = {{"a", 1}, {"b", 2}, {"c", 4}}; cout << "j1 == j2: " << (j1 == j2) << endl; cout << "j1 == j3: " << (j1 == j3) << endl; cout << "j1 != j3: " << (j1 != j3) << endl; json num1 = 10; json num2 = 20; cout << "10 < 20: " << (num1 < num2) << endl; json arr1 = {1, 2, 3}; json arr2 = {1, 2, 4}; cout << "[1,2,3] < [1,2,4]: " << (arr1 < arr2) << endl; } void test_json_pointer() { cout << "\nJSON POINTER\n"; json j; j["store"]["book"]["title"] = "C++"; j["store"]["book"]["price"] = 49.99; j["user"]["name"] = "Alice"; cout << "Исходный JSON:\n" << j.dump(2) << endl; string title = j["/store/book/title"_json_pointer]; double price = j["/store/book/price"_json_pointer]; string name = j["/user/name"_json_pointer]; cout << "/store/book/title -> " << title << endl; cout << "/store/book/price -> " << price << endl; cout << "/user/name -> " << name << endl; j["/store/book/price"_json_pointer] = 39.99; j["/user/last_login"_json_pointer] = "2025-05-21"; cout << "После изменения:\n" << j.dump(2) << endl; } int main() { int choice; do { showMainMenu(); cin >> choice; switch(choice) { case 1: test_create(); break; case 2: test_access(); break; case 3: test_modify(); break; case 4: test_file(); break; case 5: { int advChoice; do { showAdvancedMenu(); cin >> advChoice; switch(advChoice) { case 1: test_types(); break; case 2: test_comparison(); break; case 3: test_json_pointer(); break; case 0: break; default: cout << "Неверный выбор" << endl; } } while(advChoice != 0); break; } case 0: cout << "До свидания!" << endl; break; default: cout << "Неверный выбор" << endl; } } while(choice != 0); return 0; }