summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authormvel <[email protected]>2026-03-19 07:43:44 +0300
committermvel <[email protected]>2026-03-19 08:29:50 +0300
commit09f4d6f7c5d2bde0fce52df4a1b8b369fe44967c (patch)
tree79eb3e960accb09d9b1e90135c088e53e33f2fef
parent1916d58b6659a020b96f8cd1f6740cbcc496cee7 (diff)
[json] Add non-const version of `GetStringSafe` method (relates)
Странно, что такого метода не было. А он полезен, если хочешь хачить уже имеющуюся структуру. commit_hash:09763c7c08d149a27867a4cf5908b694b3024e99
-rw-r--r--library/cpp/json/writer/json_value.cpp7
-rw-r--r--library/cpp/json/writer/json_value.h1
-rw-r--r--library/cpp/json/writer/json_value_ut.cpp8
3 files changed, 16 insertions, 0 deletions
diff --git a/library/cpp/json/writer/json_value.cpp b/library/cpp/json/writer/json_value.cpp
index 6a0546fe043..22f2b2c07a2 100644
--- a/library/cpp/json/writer/json_value.cpp
+++ b/library/cpp/json/writer/json_value.cpp
@@ -455,6 +455,13 @@ namespace NJson {
return Value.String;
}
+ TString& TJsonValue::GetStringSafe() {
+ if (!IsString()) {
+ ythrow TJsonException() << "Not a string";
+ }
+ return Value.String;
+ }
+
bool TJsonValue::GetBooleanSafe(const bool defaultValue) const {
if (Type == JSON_UNDEFINED) {
return defaultValue;
diff --git a/library/cpp/json/writer/json_value.h b/library/cpp/json/writer/json_value.h
index 6b20af7f4cb..fc07466ee24 100644
--- a/library/cpp/json/writer/json_value.h
+++ b/library/cpp/json/writer/json_value.h
@@ -125,6 +125,7 @@ namespace NJson {
unsigned long long GetUIntegerSafe() const;
double GetDoubleSafe() const;
const TString& GetStringSafe() const Y_LIFETIME_BOUND;
+ TString& GetStringSafe() Y_LIFETIME_BOUND;
const TMapType& GetMapSafe() const Y_LIFETIME_BOUND;
TMapType& GetMapSafe() Y_LIFETIME_BOUND;
const TArray& GetArraySafe() const Y_LIFETIME_BOUND;
diff --git a/library/cpp/json/writer/json_value_ut.cpp b/library/cpp/json/writer/json_value_ut.cpp
index 21b396a64de..e804e541ccf 100644
--- a/library/cpp/json/writer/json_value_ut.cpp
+++ b/library/cpp/json/writer/json_value_ut.cpp
@@ -682,4 +682,12 @@ Y_UNIT_TEST_SUITE(TJsonValueTest) {
UNIT_ASSERT_VALUES_EQUAL(filled["4"].GetMapSafe().size(), 1);
UNIT_ASSERT_VALUES_EQUAL(filled["4"]["5"], TJsonValue{5});
}
+
+ Y_UNIT_TEST(GetStringSafeTest) {
+ TJsonValue json;
+ json["key"] = "value";
+ TString& valueRef = json["key"].GetStringSafe();
+ valueRef = "new_value";
+ UNIT_ASSERT_VALUES_EQUAL(json["key"].GetString(), "new_value");
+ }
} // Y_UNIT_TEST_SUITE(TJsonValueTest)