Convert an array of json objects to tsv (python)

为君一笑 提交于 2019-12-03 22:17:21

The first step is to convert from a JSON string to an array of Python objects using, for example, json.loads.

The final step is to write the Python objects to a file using, for example, csv.DictWriter.

Here is a complete program that demonstrates how to convert from a JSON string to tab-separated-values file.

import json
import csv

j = json.loads(r'''[
  {
    "x": "1",
    "y": "2",
    "z": "3"
  },
  {
    "x": "6",
    "y": "7",
    "z": "B"
  }
]''')

with open('output.tsv', 'w') as output_file:
    dw = csv.DictWriter(output_file, sorted(j[0].keys()), delimiter='\t')
    dw.writeheader()
    dw.writerows(j)

A somewhat heavy handed approach would be to use Pandas

> import sys
> import pandas as pd
> table = pd.read_json('''[
  {
    "x": "1",
    "y": "2",
    "z": "3"
  },
  {
    "x": "6",
    "y": "7",
    "z": "B"
  }
]''', orient='records')
> table.to_csv(sys.stdout, sep='\t', index=False)

x   y   z
1   2   3
6   7   B
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!