这是我的输出:
xyz information
+-----+------+------+
| A | B | C |
+-----+------+------+
| 23 | 76 | 87 |
| 76 | 36 | 37 |
| 83 | 06 | 27 |
+-----+------+------+
我想在python中将此输出转换为json格式 任何人都可以建议如何做到这一点。
答案 0 :(得分:0)
鉴于
xyz = '''+-----+------+------+
| A | B | C |
+-----+------+------+
| 23 | 76 | 87 |
| 76 | 36 | 37 |
| 83 | 06 | 27 |
+-----+------+------+'''
待办事项
import json
import collections
xyz_rows = [map(str.strip, row.split('|')[1:-1]) for row in xyz.split('\n') if '|' in row]
xyz_cols = collections.OrderedDict() # OrderedDict to preserve column order
for column in zip(*xyz_rows): # rows to columns
xyz_cols[column[0]] = column[1:]
xyz_json = json.dumps(xyz_cols)
xyz_json
包含
'{"A": ["23", "76", "83"], "B": ["76", "36", "06"], "C": ["87", "37", "27"]}'