Add and use JsonObject::foreach.

This commit is contained in:
levlam 2023-07-31 19:38:53 +03:00
parent d19b659337
commit a7b6f55d7a
3 changed files with 16 additions and 11 deletions

View File

@ -19,14 +19,6 @@
namespace td {
static td_api::object_ptr<td_api::JsonValue> get_json_value_object(const JsonValue &json_value);
static td_api::object_ptr<td_api::jsonObjectMember> get_json_value_member_object(
const std::pair<MutableSlice, JsonValue> &json_value_member) {
return td_api::make_object<td_api::jsonObjectMember>(json_value_member.first.str(),
get_json_value_object(json_value_member.second));
}
static td_api::object_ptr<td_api::JsonValue> get_json_value_object(const JsonValue &json_value) {
switch (json_value.type()) {
case JsonValue::Type::Null:
@ -39,9 +31,13 @@ static td_api::object_ptr<td_api::JsonValue> get_json_value_object(const JsonVal
return td_api::make_object<td_api::jsonValueString>(json_value.get_string().str());
case JsonValue::Type::Array:
return td_api::make_object<td_api::jsonValueArray>(transform(json_value.get_array(), get_json_value_object));
case JsonValue::Type::Object:
return td_api::make_object<td_api::jsonValueObject>(
transform(json_value.get_object().field_values_, get_json_value_member_object));
case JsonValue::Type::Object: {
vector<td_api::object_ptr<td_api::jsonObjectMember>> members;
json_value.get_object().foreach([&members](Slice name, const JsonValue &value) {
members.push_back(td_api::make_object<td_api::jsonObjectMember>(name.str(), get_json_value_object(value)));
});
return td_api::make_object<td_api::jsonValueObject>(std::move(members));
}
default:
UNREACHABLE();
return nullptr;

View File

@ -763,6 +763,12 @@ Result<string> JsonObject::get_required_string_field(Slice name) const {
return Status::Error(400, PSLICE() << "Can't find field \"" << name << '"');
}
void JsonObject::foreach(const std::function<void(Slice name, const JsonValue &value)> &callback) const {
for (auto &field_value : field_values_) {
callback(field_value.first, field_value.second);
}
}
bool has_json_object_field(const JsonObject &object, Slice name) {
for (auto &field_value : object.field_values_) {
if (field_value.first == name) {

View File

@ -14,6 +14,7 @@
#include "td/utils/Status.h"
#include "td/utils/StringBuilder.h"
#include <functional>
#include <new>
#include <type_traits>
#include <utility>
@ -492,6 +493,8 @@ class JsonObject {
Result<string> get_optional_string_field(Slice name, string default_value = string()) const;
Result<string> get_required_string_field(Slice name) const;
void foreach(const std::function<void(Slice name, const JsonValue &value)> &callback) const;
};
class JsonValue final : private Jsonable {