简体   繁体   English

将json对象数组转换为tsv(python)

[英]Convert an array of json objects to tsv (python)

Suppose that I have the following array of json objects, I want to convert them to the tsv format. 假设我有以下json对象数组,我想将它们转换为tsv格式。

[
  {
    "x": "1",
    "y": "2",
    "z": "3"
  },
  {
    "x": "6",
    "y": "7",
    "z": "B"
  }
]

Does anyone have a good solution to this? 有人对此有很好的解决方案吗? (python's json module only allow reading json object, but how to read an array of json object?) (python的json模块只允许读取json对象,但是如何读取json对象数组?)

x<TAB>y<TAB>z
1<TAB>2<TAB>3
6<TAB>7<TAB>8

The first step is to convert from a JSON string to an array of Python objects using, for example, json.loads . 第一步是使用json.loads将JSON字符串转换为Python对象数组。

The final step is to write the Python objects to a file using, for example, csv.DictWriter . 最后一步是使用csv.DictWriter将Python对象写入文件。

Here is a complete program that demonstrates how to convert from a JSON string to tab-separated-values file. 这是一个完整的程序,演示了如何从JSON字符串转换为制表符分隔值文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM