【问题标题】:How to convert to json file formate in python如何在python中转换为json文件格式
【发布时间】:2016-09-27 13:26:21
【问题描述】:

这是我的输出:

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

我想在 python 中将此输出转换为 json 格式 任何人都可以建议如何做到这一点。

【问题讨论】:

标签: python json python-2.7


【解决方案1】:

给定

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"]}'

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 2019-08-15
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    相关资源
    最近更新 更多