forked from vivek005001/viz_assist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_to_csv.py
39 lines (27 loc) · 1.24 KB
/
json_to_csv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import json
import csv
def json_to_txt(input_file, output_file):
with open(input_file, 'r',encoding='utf-8') as json_file:
data = json.load(json_file)
images = data['images']
annotations = data['annotations']
with open(output_file, 'w', encoding='utf-8') as txt_file:
txt_file.write("image,caption\n")
for image, annotation in zip(images, annotations):
txt_file.write(f"{image['file_name']},\"{annotation['caption']}\"\n")
def json_to_csv(input_file, output_file):
with open(input_file, 'r', encoding='utf-8') as json_file:
data = json.load(json_file)
images = data['images']
annotations = data['annotations']
with open(output_file, 'w', newline='', encoding='utf-8') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['image', 'caption']) # Write the header
for image, annotation in zip(images, annotations):
writer.writerow([image['file_name'], '"{}"'.format(annotation['caption'])])
# Example usage
input_file = 'annotations.json'
output_file = 'data.txt'
json_to_txt(input_file, output_file)
output_file1 = 'data.csv'
json_to_csv(input_file, output_file1)