I want to convert my dataset, which is in .json format, to .txt format. I need these files to train my model for object detection using the YOLO algorithm. I don’t want to use any online platform; I want to convert it by myself on my local PC. Please help, it would be very helpful.
Hey! I’ve worked on a few computer vision projects using YOLO, and yes — you can definitely convert a .json file to .txt format easily with Python. The key is to extract the right fields like labels and bounding boxes and format them the YOLO way. Here’s a basic script to get you started:
# Load JSON file
with open('your_file.json') as f:
data = json.load(f)
# Write to TXT in YOLO format
with open('output.txt', 'w') as f:
for item in data:
f.write(f"{item['label']} {item['x']} {item['y']} {item['width']} {item['height']}\n")
So yeah, this will help you convert a .json file to .txt format and prep your annotations for YOLO training. Let me know how it goes!
Right! Just to build on what @yanisleidi-rodriguez shared — I’ve done this several times during dataset prep, and it’s honestly one of the smoothest parts if your JSON structure is consistent. You don’t need any fancy tool — just a quick script like this:
import json
with open('data.json') as f:
json_data = json.load(f)
with open('output.txt', 'w') as output:
for obj in json_data['objects']: # Assuming your JSON is nested
output.write(f"{obj['class']} {obj['x_center']} {obj['y_center']} {obj['width']} {obj['height']}\n")
Again, the important bit when you convert a .json file to .txt format for YOLO is matching the exact keys — every dataset can differ slightly in structure. So tweak json_data[‘objects’] as needed. That’s pretty much it!
Yes, totally agree with the earlier points! I’ve been working with training pipelines for object detection for a while now, and if you’re aiming for clean training inputs, precision here matters.
Let me take it a step further — if your JSON includes multiple entries (like per image), you might need something more flexible.
Here’s a script that handles structured JSON with bounding box details:
import json
with open('data.json') as file:
data = json.load(file)
with open('output.txt', 'w') as txt_file:
for entry in data:
label = entry['label']
x_center = entry['x_center']
y_center = entry['y_center']
width = entry['width']
height = entry['height']
txt_file.write(f"{label} {x_center} {y_center} {width} {height}\n")
This gives you a clean, structured way to convert a .json file to .txt format for YOLO. Just make sure your JSON keys are correct — especially if your format comes from tools like CVAT or Labelme. Always worth validating a few outputs manually before scaling it.