在Python中将Tabular CLI输出转换为JSON格式

时间:2017-08-28 08:34:25

标签: python json parsing tabular

我需要在python中将他的输出转换为Json格式。

我该怎么做?

switch# sh mod
Mod  Ports  Module-Type                         Model              Status
---  -----  ----------------------------------- ------------------ ----------
1    48     1/2/4/8 Gbps FC/Supervisor-3        DS-C9148-K9-SUP    active *

Mod  Sw              Hw      World-Wide-Name(s) (WWN)
---  --------------  ------  --------------------------------------------------
1    6.2(17)         1.1     20:01:54:7f:ee:df:88:f8 to 20:30:54:7f:ee:df:88:f8


Mod  MAC-Address(es)                         Serial-Num
---  --------------------------------------  ----------
1    c0-8c-60-65-82-dc to c0-8c-60-65-82-df  JAF1736ALLM

输入1:https://i.stack.imgur.com/EGsY4.jpg

输入2:https://i.stack.imgur.com/aDGcB.jpg

2 个答案:

答案 0 :(得分:1)

我有一个解决方案,但它并不漂亮。假设您的整个输出都在text

import re
lines = text.split("\n")
keylines = [line for i, line in enumerate(lines) if len(lines)>(i+1) and "---" in lines[i+1]]
vallines = [line for i, line in enumerate(lines) if i!=0 and "---" in lines[i-1]]
keys = re.split("  +", "  ".join(keylines))
vals = re.split("  +", "  ".join(vallines))
result = dict(zip(keys, vals))

输出:

{
  "Mod": "1",
  "Ports": "48",
  "Module-Type": "1/2/4/8 Gbps FC/Supervisor-3",
  "Model": "DS-C9148-K9-SUP",
  "Status": "active *",
  "Sw": "6.2(17)",
  "Hw": "1.1",
  "World-Wide-Name(s) (WWN)": "20:01:54:7f:ee:df:88:f8 to 20:30:54:7f:ee:df:88:f8",
  "MAC-Address(es)": "c0-8c-60-65-82-dc to c0-8c-60-65-82-df",
  "Serial-Num": "JAF1736ALLM"
}

它做出以下假设,并且当它们不成立时会中断:

  • 没有值连续包含多个空格。
  • "字段"。
  • 之间至少有两个空格
  • 在破折号的行中,至少有一个长度为3个虚线的段。

答案 1 :(得分:0)

您可以使用' ---'分隔符定义每个键和值行的切片以构建每个键值。 (从你的例子中,我猜测有多个" Mod" s,具有唯一的Mod值,所以我将这个字段用于整个累加器密钥。)

const HOCUpdater = defaultState => BaseComponent => {
  return class Updater extends React.Component {
    constructor(props,context){
      super(props,context);
      this.state = Object.assign({},defaultState,this.state);
    }
    componentWillReceiveProps(nextProps){
      this.setState(nextProps);
    }
    render(){
      return createElement(BaseComponent,{...this.state});
    }
  }
}

打印:

from collections import defaultdict
import re
from itertools import groupby

sample = """\
Mod  Ports  Module-Type                         Model              Status
---  -----  ----------------------------------- ------------------ ----------
1    48     1/2/4/8 Gbps FC/Supervisor-3        DS-C9148-K9-SUP    active *
2    48     1/2/4/8 Gbps FC/Supervisor-3        DS-C9148-K9-SUP    active *

Mod  Sw              Hw      World-Wide-Name(s) (WWN)
---  --------------  ------  --------------------------------------------------
1    6.2(17)         1.1     20:01:54:7f:ee:df:88:f8 to 20:30:54:7f:ee:df:88:f8
2    6.2(17)         1.1     20:01:54:7f:ee:df:88:f8 to 20:30:54:7f:ee:df:88:f8

Mod  MAC-Address(es)                         Serial-Num
---  --------------------------------------  ----------
1    c0-8c-60-65-82-dc to c0-8c-60-65-82-df  JAF1736ALLM
2    c0-8c-60-65-82-ec to c0-8c-60-65-82-ef  JAF1736AXXX

Xbar Ports Module-Type Model Status
---- ----- ----------- ----- ------
1    0     Fabric 1    ABC   ok

Xbar Sw Hw
---- -- ---
1    NA 1.0

"""

all_input_lines = sample.splitlines()
mod_accum = defaultdict(dict)
xbar_accum = defaultdict(dict)

for is_blank, input_lines_iter in groupby(all_input_lines, 
                                          key=lambda s: not bool(s.strip())):
    input_lines = list(input_lines_iter)
    if is_blank:
        continue

    # assume first two lines are field names and separator dashes
    names, dashes = input_lines[:2]

    # make sure dashes line is all '---' separators
    if not all(ss == set('-') for ss in map(set, dashes.split())):
        print("invalid line group found, skipping...")
        print('-'*40)
        print('\n'.join(input_lines))
        print('-'*40)
        continue

    # use regex to get start/end of each '---' divider, and make slices
    spans = (match.span() for match in re.finditer('-+', dashes))
    slices = [slice(sp[0], sp[1]+1) for sp in spans]

    names = [names[sl].rstrip() for sl in slices]

    # is this a module or an xbar?
    if 'Mod' in names:
        key = 'Mod'
        accum = mod_accum
    elif 'Xbar' in names:
        key = 'Xbar'
        accum = xbar_accum
    else:
        raise ValueError("no Mod or Xbar name in row names ({})".format(
                            ",".join(names)))

    for line in input_lines:
        # use slices to extract data from values, make into a dict
        row_dict = dict(zip(names, (line[sl].rstrip() for sl in slices)))

        # accumulate these values into any previous ones collected for this Mod
        accum[row_dict[key]].update(row_dict)

# print out what we got
import json
all_data = {"Modules": mod_accum, "Xbars": xbar_accum}
print(json.dumps(all_data, indent=2))