json_to_csv.py 1.0 KB

12345678910111213141516171819202122232425262728
  1. import argparse
  2. import json
  3. import os
  4. def work(json_fold):
  5. json_list = os.listdir(json_fold)
  6. for json_path in json_list:
  7. path = json_fold + '/' + json_path
  8. # 处理json文件
  9. if str(path).endswith('.json'):
  10. with open(path, "r", encoding="utf-8") as f:
  11. content = json.load(f)
  12. # 将 JSON 数据写入 CSV 文件
  13. csv_path = str(path).replace('json', 'jpg') + '.csv'
  14. with open(csv_path, mode='w', newline='') as csv_file:
  15. # 使用 DictWriter 而不是 csv.DictWriter,因为需要将 JSON 中的键作为列名
  16. for point in content['shapes']:
  17. line = str(point['points'][0][0]) + ' ' + str(point['points'][0][1]) + '\n'
  18. print(line)
  19. csv_file.write(line)
  20. if __name__ == "__main__":
  21. parser = argparse.ArgumentParser()
  22. parser.add_argument('--json_fold', type=str, default='./my_dataset_origin')
  23. args = parser.parse_args()
  24. work(args.json_fold)