From 867c3c79086ad2f0c27567adbc345c504c1f7afe Mon Sep 17 00:00:00 2001 From: dragonknightk <37928252+dragonknightk@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:27:42 +0800 Subject: [PATCH] fix(schema): decode nested Array and Map records as Record objects Closes issue 172 ### Motivation Decoding a Record with Array(Array(Record)) leaves the inner values as dicts, so decoded.b[0][0].a raises AttributeError. This happens because Record.__init__ only handles the first level, and both JsonSchema.decode and AvroSchema.decode go through this path. ### Modifications Record.__init__ now walks Array and Map fields recursively and turns any dict that matches a Record field into a Record, at any depth. The same fix also covers nested Map combinations (Map of Map, Array of Map, Map of Array). There are no C++ binding changes. ### Verifying this change Added JsonSchema decode tests for the issue 172 reproduction (Array of Array of Record) and for the nested Map combinations above. The tests check that the inner value is a Record and that its field is readable, plus a JSON encode/decode round-trip for the array case. Existing one-level Array(Record) and Map(Record) JSON and Avro encode/decode tests still cover the previous behavior. Signed-off-by: dragonknightk <37928252+dragonknightk@users.noreply.github.com> --- pulsar/schema/definition.py | 41 +++++++++++++------------------ tests/schema_test.py | 48 +++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 24 deletions(-) diff --git a/pulsar/schema/definition.py b/pulsar/schema/definition.py index d2796d2f..fccc769f 100644 --- a/pulsar/schema/definition.py +++ b/pulsar/schema/definition.py @@ -75,30 +75,8 @@ def __init__(self, default=None, required_default=False, required=False, *args, for k, value in self._fields.items(): if k in kwargs: - if isinstance(value, Record) and isinstance(kwargs[k], dict): - # Use dict init Record object - copied = copy.copy(value) - copied.__init__(**kwargs[k]) - self.__setattr__(k, copied) - elif isinstance(value, Array) and isinstance(kwargs[k], list) and len(kwargs[k]) > 0 \ - and isinstance(value.array_type, Record) and isinstance(kwargs[k][0], dict): - arr = [] - for item in kwargs[k]: - copied = copy.copy(value.array_type) - copied.__init__(**item) - arr.append(copied) - self.__setattr__(k, arr) - elif isinstance(value, Map) and isinstance(kwargs[k], dict) and len(kwargs[k]) > 0 \ - and isinstance(value.value_type, Record) and isinstance(list(kwargs[k].values())[0], dict): - dic = {} - for mapKey, mapValue in kwargs[k].items(): - copied = copy.copy(value.value_type) - copied.__init__(**mapValue) - dic[mapKey] = copied - self.__setattr__(k, dic) - else: - # Value was overridden at constructor - self.__setattr__(k, kwargs[k]) + # Value was overridden at constructor + self.__setattr__(k, _hydrate_field(value, kwargs[k])) elif isinstance(value, Record): # Value is a subrecord self.__setattr__(k, value) @@ -523,6 +501,21 @@ def default(self): return None +def _hydrate_field(field, value): + # Rebuild Record instances from dicts produced by JSON/Avro decode, + # including nested Array and Map fields. + if isinstance(field, Record) and isinstance(value, dict): + copied = copy.copy(field) + copied.__init__(**value) + return copied + if isinstance(field, Array) and isinstance(value, list): + return [_hydrate_field(field.array_type, item) for item in value] + if isinstance(field, Map) and isinstance(value, dict): + return {map_key: _hydrate_field(field.value_type, map_value) + for map_key, map_value in value.items()} + return value + + # Python3 has no `unicode` type, so here we use a tricky way to check if the type of `x` is `unicode` in Python2 # and also make it work well with Python3. def is_unicode(x): diff --git a/tests/schema_test.py b/tests/schema_test.py index 42b65905..0d5880ff 100755 --- a/tests/schema_test.py +++ b/tests/schema_test.py @@ -436,6 +436,54 @@ class Example(Record): self.assertEqual(r2.__class__.__name__, 'Example') self.assertEqual(r2, r) + def test_serialize_json_nested_array_of_records(self): + # Expected values come from issue 172: JsonSchema.decode of + # Array(Array(Record)) should rebuild the inner dict as a Record, + # so nested_objects.a is readable. One-level Array(Record) already + # worked; deeper nesting previously left dicts in place. + class A(Record): + a = String() + + class B(Record): + b = Array(Array(A())) + + s = JsonSchema(B) + decoded = s.decode('{"b": [[{"a": "hello world"}]]}') + self.assertIsInstance(decoded.b[0][0], A) + self.assertEqual(decoded.b[0][0].a, 'hello world') + + original = B(b=[[A(a='hello world')]]) + roundtrip = s.decode(s.encode(original)) + self.assertEqual(roundtrip, original) + self.assertIsInstance(roundtrip.b[0][0], A) + + def test_serialize_json_nested_map_of_records(self): + # Same Record.__init__ hydration path as issue 172, for nested + # Map/Array combinations of Record that were also left as dicts. + class A(Record): + a = String() + + class MapMap(Record): + values = Map(Map(A())) + + class ArrayMap(Record): + values = Array(Map(A())) + + class MapArray(Record): + values = Map(Array(A())) + + decoded = JsonSchema(MapMap).decode('{"values": {"k": {"n": {"a": "hello"}}}}') + self.assertIsInstance(decoded.values['k']['n'], A) + self.assertEqual(decoded.values['k']['n'].a, 'hello') + + decoded = JsonSchema(ArrayMap).decode('{"values": [{"n": {"a": "hello"}}]}') + self.assertIsInstance(decoded.values[0]['n'], A) + self.assertEqual(decoded.values[0]['n'].a, 'hello') + + decoded = JsonSchema(MapArray).decode('{"values": {"k": [{"a": "hello"}]}}') + self.assertIsInstance(decoded.values['k'][0], A) + self.assertEqual(decoded.values['k'][0].a, 'hello') + def test_serialize_avro(self): class Example(Record): a = Integer()