userver: en/testsuite/utils/json_util.py Source File
Loading...
Searching...
No Matches
json_util.py
1import json
2
3from testsuite.utils import object_hook as object_hook_util
4
5
6def loads(string, *args, **kwargs):
7 """Helper function that wraps ``json.loads``.
8
9 Automatically passes the object_hook for BSON type conversion.
10 """
11
12 object_hook = kwargs.pop('object_hook', None)
13 kwargs['object_hook'] = object_hook_util.build_object_hook(
14 object_hook=object_hook,
15 )
16 return json.loads(string, *args, **kwargs)
17
18
19def substitute(json_obj, *, object_hook=None):
20 """Create transformed json by making substitutions:
21
22 {"$mockserver": "/path", "$schema": true} -> "http://localhost:9999/path"
23 {"$dateDiff": 10} -> datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None) + timedelta(seconds=10)
24 """
25 hook = object_hook_util.build_object_hook(object_hook=object_hook)
26 return object_hook_util.substitute(json_obj, hook)
27
28
29def dumps(obj, *args, **kwargs):
30 """Helper function that wraps ``json.dumps``.
31
32 This function does NOT support ``bson.binary.Binary`` and
33 ``bson.code.Code`` types. It just passes ``default`` argument to
34 ``json.dumps`` function.
35 """
36 kwargs['ensure_ascii'] = kwargs.get('ensure_ascii', False)
37 kwargs['sort_keys'] = kwargs.get('sort_keys', True)
38 kwargs['indent'] = kwargs.get('indent', 2)
39 kwargs['separators'] = kwargs.get('separators', (',', ': '))
40 return json.dumps(obj, *args, **kwargs)