转换JSON对象的数组TSV(蟒蛇) [英] Convert an array of json objects to tsv (python)

查看:253
本文介绍了转换JSON对象的数组TSV(蟒蛇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下的JSON对象数组,我想将它们转换为TSV格式。

  [
  {
    ×:1,
    Y:2,
    Z:3
  },
  {
    ×:6,
    Y:7,
    Z:B的
  }
]

有没有人有一个很好的解决这个? (Python的json模块只允许读json对象,而是怎样读书JSON对象的数组?)

  X<标签> Y'LT;标签> Z
1<标签> 2';标签> 3
6≤标签> 7 LT;标签> 8


解决方案

第一步是从一个JSON字符串转换为使用,例如Python对象的数组, json.loads

最后一步是使用,例如编写Python对象到一个文件中, csv.DictWriter

下面是一个演示如何从一个JSON字符串制表符分隔值文件转换成一个完整的程序。

 进口JSON
导入CSVJ = json.loads(R'''[
  {
    ×:1,
    Y:2,
    Z:3
  },
  {
    ×:6,
    Y:7,
    Z:B的
  }
]''')开放('output.tsv','W')为OUTPUT_FILE:
    DW = csv.DictWriter(OUTPUT_FILE,分类(J [0]键()),分隔符='\\ t')
    dw.writeheader()
    dw.writerows(J)

Suppose that I have the following array of json objects, I want to convert them to the tsv format.

[
  {
    "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?)

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.

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)

这篇关于转换JSON对象的数组TSV(蟒蛇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆