0e78679ecc8239560847af12376a7a72345eab5b
[csit.git] / resources / libraries / python / parsers / JsonParser.py
1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Used to parse JSON files or JSON data strings to dictionaries"""
15
16 import json
17 from os import uname
18
19
20 class JsonParser(object):
21     """Parses JSON data string or files containing JSON data strings"""
22     def __init__(self):
23         pass
24
25     @staticmethod
26     def parse_data(json_data):
27         """Return list parsed from JSON data string.
28
29         Translates JSON data into list of values/dictionaries/lists.
30
31         :param json_data: Data in JSON format.
32         :type json_data: str
33         :return: JSON data parsed as python list.
34         :rtype: list
35         """
36         if "4.2.0-42-generic" in uname():
37             # TODO: remove ugly workaround
38             # On Ubuntu14.04 the VAT console returns "error:misc" even after
39             # some commands execute correctly. This causes problems
40             # with parsing JSON data.
41             known_errors = ["sw_interface_dump error: Misc",
42                             "lisp_eid_table_dump error: Misc",
43                             "show_lisp_status error: Misc",
44                             "lisp_map_resolver_dump error: Misc",
45                             "show_lisp_pitr error: Misc",
46                             "snat_static_mapping_dump error: Misc",
47                            ]
48             for item in known_errors:
49                 if item in json_data:
50                     json_data = json_data.replace(item, "")
51                     print("Removing API error: *{0}* "
52                           "from JSON output.".format(item))
53         parsed_data = json.loads(json_data)
54         return parsed_data
55
56     @staticmethod
57     def parse_file(json_file):
58         """Return list parsed from file containing JSON string.
59
60         Translates JSON data found in file into list of
61         values/dictionaries/lists.
62
63         :param json_file: File with JSON type data.
64         :type json_file: str
65         :return: JSON data parsed as python list.
66         :rtype: list
67         """
68         input_data = open(json_file).read()
69         parsed_data = JsonParser.parse_data(input_data)
70         return parsed_data