1 # Copyright 2017 Red Hat Inc & Xena Networks.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
16 # Dan Amzulescu, Xena Networks
17 # Christian Trautman, Red Hat Inc.
19 """JSON utility module"""
27 _LOGGER = logging.getLogger(__name__)
28 _LOCALE = locale.getlocale()[1]
30 def create_segment(header_type, encode_64_string):
32 Create segment for JSON file
33 :param header_type: Type of header as string
34 :param encode_64_string: 64 byte encoded string value of the hex bytes
35 :return: segment as dictionary
38 "SegmentType": header_type.upper(),
39 "SegmentValue": encode_64_string,
40 "ItemID": str(uuid.uuid4()),
45 def decode_byte_array(enc_str):
46 """ Decodes the base64-encoded string to a byte array
47 :param enc_str: The base64-encoded string representing a byte array
48 :return: The decoded byte array
50 dec_string = base64.b64decode(enc_str)
52 barray.extend(dec_string)
56 def encode_byte_array(byte_arr):
57 """ Encodes the byte array as a base64-encoded string
58 :param byte_arr: A bytearray containing the bytes to convert
59 :return: A base64 encoded string
61 enc_string = base64.b64encode(bytes(byte_arr))
65 def read_json_file(json_file):
67 Read the json file path and return a dictionary of the data
68 :param json_file: path to json file
69 :return: dictionary of json data
72 with open(json_file, 'r', encoding=_LOCALE) as data_file:
73 file_data = json.loads(data_file.read())
74 except ValueError as exc:
75 # general json exception, Python 3.5 adds new exception type
76 _LOGGER.exception("Exception with json read: %s", exc)
78 except IOError as exc:
80 'Exception during file open: %s file=%s', exc, json_file)
85 def write_json_file(json_data, output_path):
87 Write out the dictionary of data to a json file
88 :param json_data: dictionary of json data
89 :param output_path: file path to write output
90 :return: Boolean if success
93 with open(output_path, 'w', encoding=_LOCALE) as fileh:
94 json.dump(json_data, fileh, indent=2, sort_keys=True,
97 except ValueError as exc:
98 # general json exception, Python 3.5 adds new exception type
100 "Exception with json write: %s", exc)
102 except IOError as exc:
104 'Exception during file write: %s file=%s', exc, output_path)