|
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
|
|
|
import json |
|
17
|
|
|
import logging |
|
18
|
|
|
|
|
19
|
|
|
from st2client import formatters |
|
20
|
|
|
from st2client.utils import jsutil |
|
21
|
|
|
|
|
22
|
|
|
|
|
23
|
|
|
LOG = logging.getLogger(__name__) |
|
24
|
|
|
|
|
25
|
|
|
|
|
26
|
|
|
class Json(formatters.Formatter): |
|
27
|
|
|
|
|
28
|
|
|
@classmethod |
|
29
|
|
|
def format(self, subject, *args, **kwargs): |
|
|
|
|
|
|
30
|
|
|
attributes = kwargs.get('attributes', None) |
|
31
|
|
|
if type(subject) is str: |
|
32
|
|
|
subject = json.loads(subject) |
|
33
|
|
|
elif not isinstance(subject, (list, tuple)) and not hasattr(subject, '__iter__'): |
|
34
|
|
|
doc = subject if isinstance(subject, dict) else subject.__dict__ |
|
35
|
|
|
keys = doc.keys() if not attributes or 'all' in attributes else attributes |
|
36
|
|
|
docs = jsutil.get_kvps(doc, keys) |
|
37
|
|
|
else: |
|
38
|
|
|
docs = [] |
|
39
|
|
|
for item in subject: |
|
40
|
|
|
doc = item if isinstance(item, dict) else item.__dict__ |
|
41
|
|
|
keys = doc.keys() if not attributes or 'all' in attributes else attributes |
|
42
|
|
|
docs.append(jsutil.get_kvps(doc, keys)) |
|
43
|
|
|
return json.dumps(docs, indent=4, sort_keys=True) |
|
44
|
|
|
|