Skip to content

Commit dee1406

Browse files
authored
Merge pull request #89 from cwacek/feature/support-top-level-arrays
Fix #88. Properly construct wrappers for top level array constraints
2 parents a0a560d + 5cc4599 commit dee1406

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

python_jsonschema_objects/wrapper_types.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -275,10 +275,16 @@ def create(name, item_constraint=None, **addl_constraints):
275275

276276
item_constraint = classbuilder.TypeProxy(type_array)
277277

278+
elif isdict and item_constraint.get('type') == 'object':
279+
""" We need to create a ProtocolBase object for this anonymous definition"""
280+
uri = "{0}_{1}".format(name, "<anonymous_list_type>")
281+
item_constraint = klassbuilder.construct(
282+
uri, item_constraint)
283+
278284
props['__itemtype__'] = item_constraint
279285

280286
props.update(addl_constraints)
281287

282288
validator = type(str(name), (ArrayWrapper,), props)
283289

284-
return validator
290+
return validator

test/test_regression_88.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import pytest
2+
import json
3+
4+
import python_jsonschema_objects as pjs
5+
6+
7+
def test_nested_arrays_work_fine():
8+
schema = {
9+
"$schema": "http://json-schema.org/draft-04/schema",
10+
"title": "Example1",
11+
"type": "object",
12+
"properties": {
13+
"name": {
14+
"type": "array",
15+
"items": {
16+
"type": "object",
17+
"properties": {
18+
"name": {"type": "string"}
19+
}
20+
}
21+
}
22+
}
23+
}
24+
25+
ns1 = pjs.ObjectBuilder(schema).build_classes()
26+
j1 = ns1.Example1.from_json(json.dumps({'name': [{'value':'foo'}, {'value':'bar'}]}))
27+
assert j1.name[0].value == 'foo'
28+
assert j1.name[1].value == 'bar'
29+
30+
31+
def test_top_level_arrays_are_converted_to_objects_properly():
32+
schema = {
33+
"$schema": "http://json-schema.org/draft-04/schema",
34+
"title": "Example2",
35+
"type": "array",
36+
"items": {
37+
"type": "object",
38+
"properties": {
39+
"name": {"type": "string"}
40+
}
41+
}
42+
}
43+
44+
ns2 = pjs.ObjectBuilder(schema).build_classes()
45+
j2 = ns2.Example2.from_json(json.dumps([{'name': 'foo'}, {'name': 'bar'}]))
46+
assert not isinstance(j2[0], dict) # Out[173]: {'name': 'foo'}
47+
assert j2[0].name == 'foo'
48+
assert j2[1].name == 'bar'
49+

0 commit comments

Comments
 (0)