Forum Discussion
nsmcan
Dec 08, 2022Nimbostratus
Here is a piece of code I created recently, which works well for my needs. It might be updated with more 'declarative' words, where a word is a key and its omitted value is 'True':
declarative_keys = ['disabled', 'internal', 'ip-forward', 'vlans-enabled']
def parse_tmsh_one_line_output(out):
"""
Parses output of a tmsh command produced in machine-readable format with the 'one-line' option
@param out: Command output
@return: Parsed dictionary
"""
def parse_layer(tokens):
"""
Parses one dictionary layer from the tokens
@param list tokens: string tokens
@return: parsed dictionary, leftover tokens
"""
result = {}
is_key = True # The first token will be a key
key = None
while tokens:
token = tokens.pop(0)
if is_key:
key = token
if key in declarative_keys:
result[key] = True
continue
if key == '}':
break
is_key = False
else:
value = token
is_key = True
if value == '{':
result[key], tokens = parse_layer(tokens)
continue
if value.startswith('"'):
tokens.insert(0, value[1:])
parts = []
while tokens:
token = tokens.pop(0)
if token.endswith('"') and not token.endswith('\\"'):
parts.append(token[:-1])
break
parts.append(token)
value = ' '.join(parts)
result[key] = value.replace('\\"', '"')
# end while
return result, tokens
_tokens = out.split(' ')
parsed, _ = parse_layer(_tokens)
return parsed