Returns a validator for a JSON object. If the property is missing, it is treated as if it were {}. Otherwise, it must be a dict. If validate_value=False, it's treated as if it were (lambda x: x) - i.e. any value is considered valid, and is unchanged. If validate_value is a type or
(validate_value=False)
| 251 | |
| 252 | |
| 253 | def object(validate_value=False): |
| 254 | """Returns a validator for a JSON object. |
| 255 | |
| 256 | If the property is missing, it is treated as if it were {}. Otherwise, it must |
| 257 | be a dict. |
| 258 | |
| 259 | If validate_value=False, it's treated as if it were (lambda x: x) - i.e. any |
| 260 | value is considered valid, and is unchanged. If validate_value is a type or a |
| 261 | tuple, it's treated as if it were json.of_type(validate_value). |
| 262 | |
| 263 | Every value in the dict is replaced with validate_value(value) in-place, propagating |
| 264 | any exceptions raised by the latter. If validate_value is a type or a tuple, it is |
| 265 | treated as if it were json.of_type(validate_value). Keys are not affected. |
| 266 | """ |
| 267 | |
| 268 | if isinstance(validate_value, type) or isinstance(validate_value, tuple): |
| 269 | validate_value = of_type(validate_value) |
| 270 | |
| 271 | def validate(value): |
| 272 | if value == (): |
| 273 | return {} |
| 274 | |
| 275 | of_type(dict)(value) |
| 276 | if validate_value: |
| 277 | for k, v in value.items(): |
| 278 | try: |
| 279 | value[k] = validate_value(v) |
| 280 | except (TypeError, ValueError) as exc: |
| 281 | raise type(exc)(f"[{repr(k)}] {exc}") |
| 282 | return value |
| 283 | |
| 284 | return validate |
| 285 | |
| 286 | |
| 287 | def repr(value): |
searching dependent graphs…