how to convert JSON data to .tsv file using python.

Viewed 3206

My json data looks like this :

data ={
    "time": "2018-10-02T10:19:48+00:00",
    "class": "NOTIFICATION",
    "type": "Access Control",
    "event": "Window/Door",
    "number": -61
}

Desired output have to be like this:

time   class  type   event   number 
2018-10-02T10:19:48+00:00  NOTIFICATION  Access Control  Window/Door -61

could anyone help me out, Thanks in advance

1 Answers

I think it's the same as converting JSON to csv, but instead of using the comma you can use tab as a delimeter, as follows:

import json
import csv

# input data
json_file = open("data.json", "r")
json_data = json.load(json_file)
json_file.close()

data = json.loads(json_data)

tsv_file = open("data.tsv", "w")
tsv_writer = csv.writer(tsv_file, delimiter='\t')

tsv_writer.writerow(data[0].keys()) # write the header

for row in data: # write data rows
    tsv_writer.writerow(row.values())

tsv_file.close()

The above code will work if you json file has multiple data rows. If you have only one data row, the below code should work for you:

tsv_writer.writerow(data.keys()) # write the header
tsv_writer.writerow(data.values()) # write the values

Hope this helps.

Related