-1

Here is my output:

xyz information
+-----+------+------+
| A   | B    |  C   |
+-----+------+------+
| 23  |  76  | 87   |
| 76  |  36  | 37   |
| 83  |  06  | 27   |
+-----+------+------+

I want to convert this output to json format in python can anybody suggest how to do that.

Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
Md Salim
  • 51
  • 6

1 Answers1

1

Given

xyz = '''+-----+------+------+
| A   | B    |  C   |
+-----+------+------+
| 23  |  76  | 87   |
| 76  |  36  | 37   |
| 83  |  06  | 27   |
+-----+------+------+'''

Do

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 contains

'{"A": ["23", "76", "83"], "B": ["76", "36", "06"], "C": ["87", "37", "27"]}'
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119