Skip to content

Commit 21fcf58

Browse files
authored
feat: allow querying of json objects stored as strings (#4399)
Signed-off-by: Roman Gershman <roman@dragonflydb.io>
1 parent 1c0f22f commit 21fcf58

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

src/server/json_family.cc

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -657,11 +657,29 @@ bool LegacyModeIsEnabled(const std::vector<std::pair<std::string_view, WrappedJs
657657

658658
OpResult<std::string> OpJsonGet(const OpArgs& op_args, string_view key,
659659
const JsonGetParams& params) {
660-
OpResult<JsonType*> result = GetJson(op_args, key);
661-
RETURN_ON_BAD_STATUS(result);
660+
auto it = op_args.GetDbSlice().FindReadOnly(op_args.db_cntx, key).it;
661+
if (!IsValid(it))
662+
return OpStatus::KEY_NOTFOUND;
663+
664+
const JsonType* json_ptr = nullptr;
665+
JsonType json;
666+
if (it->second.ObjType() == OBJ_JSON) {
667+
json_ptr = it->second.GetJson();
668+
} else if (it->second.ObjType() == OBJ_STRING) {
669+
string tmp;
670+
it->second.GetString(&tmp);
671+
auto parsed_json = ShardJsonFromString(tmp);
672+
if (!parsed_json) {
673+
return OpStatus::WRONG_TYPE;
674+
}
675+
json.swap(*parsed_json);
676+
json_ptr = &json;
677+
} else {
678+
return OpStatus::WRONG_TYPE;
679+
}
662680

663681
const auto& paths = params.paths;
664-
const JsonType& json_entry = *(result.value());
682+
const JsonType& json_entry = *json_ptr;
665683

666684
if (paths.empty()) {
667685
// this implicitly means that we're using . which

src/server/json_family_test.cc

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2998,4 +2998,23 @@ TEST_F(JsonFamilyTest, MergeLegacy) {
29982998
EXPECT_EQ(resp, R"({"y":{"doubled":true},"z":{"answers":["xxx","yyy"],"doubled":false}})");
29992999
}
30003000

3001+
TEST_F(JsonFamilyTest, GetString) {
3002+
string json = R"(
3003+
{ "a": "b",
3004+
"c": {
3005+
"d": "e",
3006+
"f": "g"
3007+
}
3008+
}
3009+
)";
3010+
3011+
auto resp = Run({"SET", "json", json});
3012+
EXPECT_THAT(resp, "OK");
3013+
resp = Run({"JSON.GET", "json", "$.c"});
3014+
EXPECT_EQ(resp, R"([{"d":"e","f":"g"}])");
3015+
Run({"SET", "not_json", "not_json"});
3016+
resp = Run({"JSON.GET", "not_json", "$.c"});
3017+
EXPECT_THAT(resp, ErrArg("WRONGTYPE"));
3018+
}
3019+
30013020
} // namespace dfly

0 commit comments

Comments
 (0)