1
0
mirror of https://github.com/kellyjonbrazil/jc.git synced 2025-06-19 00:17:51 +02:00

add text_kv function

This commit is contained in:
Kelly Brazil
2022-02-24 14:53:26 -08:00
parent 2d6f666fa4
commit 3d01356461

View File

@ -38,6 +38,7 @@ Examples:
$ nmcli | jc --nmcli -p -r $ nmcli | jc --nmcli -p -r
[] []
""" """
import re
from typing import List, Dict, Optional from typing import List, Dict, Optional
import jc.utils import jc.utils
@ -87,15 +88,30 @@ def _normalize_key(keyname: str) -> str:
def _normalize_value(value: str) -> Optional[str]: def _normalize_value(value: str) -> Optional[str]:
value = value.strip() value = value.strip()
if value == '""':
value = ''
if value == '--': if value == '--':
return None return None
if value.startswith('"') and value.endswith('"'):
value = value.strip('"')
return value return value
def _add_text_kv(key: str, value: str) -> Optional[Dict]:
"""
Add keys with _text suffix if there is a text description inside
paranthesis at the end of a value. The value of the _text field will
only be the text inside the parenthesis. This allows cleanup of the
original field (convert to int/float/etc) without losing information.
"""
if value and '(' in value and value.endswith(')'):
new_val = re.search(r'\((\w+)\)$', value)
if new_val:
return ({key + '_text': new_val.group(1)})
return None
def _device_show_parse(data: str) -> List[Dict]: def _device_show_parse(data: str) -> List[Dict]:
raw_output: List = [] raw_output: List = []
@ -114,6 +130,10 @@ def _device_show_parse(data: str) -> List[Dict]:
item.update({key_n: value_n}) item.update({key_n: value_n})
text_kv = _add_text_kv(key_n, value_n)
if text_kv:
item.update(text_kv)
# get final item # get final item
if item: if item:
raw_output.append(item) raw_output.append(item)
@ -132,6 +152,10 @@ def _connection_show_x_parse(data: str) -> List[Dict]:
value_n = _normalize_value(value) value_n = _normalize_value(value)
item.update({key_n: value_n}) item.update({key_n: value_n})
text_kv = _add_text_kv(key_n, value_n)
if text_kv:
item.update(text_kv)
if item: if item:
raw_output.append(item) raw_output.append(item)