5

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

9
  • Is your data already stored as dictionary, or string? Commented Nov 15, 2018 at 1:31
  • @TeeKea yeah its string Commented Nov 15, 2018 at 3:05
  • If you are reading json data from a file, or a string, then my answer below should help you. Commented Nov 15, 2018 at 3:21
  • 1
    Can you check my updated answer (the code in the bottom)? Commented Nov 15, 2018 at 4:21
  • 1
    Please mark the answer as Accepted if it worked for you. If not, tell us your current problem. Thanks. Commented Nov 15, 2018 at 21:31

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.