Passed
Push — develop ( f534b1...a82689 )
by Plexxi
06:09 queued 03:13
created

GenericJSON   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 6
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 10
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A default() 0 5 3
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
try:
17
    import simplejson as json
18
    from simplejson import JSONEncoder
19
except ImportError:
20
    import json
21
    from json import JSONEncoder
22
23
import six
24
25
26
__all__ = [
27
    'json_encode',
28
    'json_loads',
29
    'try_loads'
30
]
31
32
33
class GenericJSON(JSONEncoder):
34
    def default(self, obj):  # pylint: disable=method-hidden
35
        if hasattr(obj, '__json__') and six.callable(obj.__json__):
36
            return obj.__json__()
37
        else:
38
            return JSONEncoder.default(self, obj)
39
40
41
def json_encode(obj, indent=4):
42
    return json.dumps(obj, cls=GenericJSON, indent=indent)
43
44
45
def load_file(path):
46
    with open(path, 'r') as fd:
47
        return json.load(fd)
48
49
50
def json_loads(obj, keys=None):
51
    """
52
    Given an object, this method tries to json.loads() the value of each of the keys. If json.loads
53
    fails, the original value stays in the object.
54
55
    :param obj: Original object whose values should be converted to json.
56
    :type obj: ``dict``
57
58
    :param keys: Optional List of keys whose values should be transformed.
59
    :type keys: ``list``
60
61
    :rtype ``dict`` or ``None``
62
    """
63
    if not obj:
64
        return None
65
66
    if not keys:
67
        keys = obj.keys()
68
69
    for key in keys:
70
        try:
71
            obj[key] = json.loads(obj[key])
72
        except:
73
            pass
74
    return obj
75
76
77
def try_loads(s):
78
    try:
79
        return json.loads(s) if s and isinstance(s, six.string_types) else s
80
    except:
81
        return s
82