今日已更新 101 条资讯 | 累计 23238 条内容
关于我们

Building a Zero-Dependency CSV-to-JSON Converter

BlackyDoe 2026年07月23日 23:51 0 次阅读 来源:Dev.to

Sometimes you export a spreadsheet and the next tool in your pipeline wants JSON instead. Pulling in pandas for that feels like overkill — Python's standard library already has everything needed. Here's a small converter that does it in a handful of lines, no third-party packages required. 1. Reading the CSV csv.DictReader turns each row into a dictionary keyed by the header row automatically — no manual header parsing needed. import csv def read_csv ( csv_path ): with open ( csv_path , newline = "" , encoding = " utf-8 " ) as f : reader = csv . DictReader ( f ) return list ( reader ) Wrapping the result in list() consumes the whole reader up front, which is fine for small-to-medium files and much simpler to reason about than lazily iterating later. 2. Writing the JSON import json def write_json ( rows , json_path ): with open ( json_path , " w " , encoding = " utf-8 " ) as f : json . dump ( rows , f , indent = 2 ) indent=2 keeps the output human-readable, which matters if anyone will actually open the file to sanity-check it. 3. Wiring it together def csv_to_json ( csv_path , json_path ): rows = read_csv ( csv_path ) write_json ( rows , json_path ) return len ( rows ) Returning the row count gives a quick sanity check — if you expected 500 contacts and it says 3, something upstream went wrong before you even open the output file. 4. The full script, start to end import csv import json def read_csv ( csv_path ): with open ( csv_path , newline = "" , encoding = " utf-8 " ) as f : reader = csv . DictReader ( f ) return list ( reader ) def write_json ( rows , json_path ): with open ( json_path , " w " , encoding = " utf-8 " ) as f : json . dump ( rows , f , indent = 2 ) def csv_to_json ( csv_path , json_path ): rows = read_csv ( csv_path ) write_json ( rows , json_path ) return len ( rows ) if __name__ == " __main__ " : count = csv_to_json ( " contacts.csv " , " contacts.json " ) print ( f " Converted { count } rows -> contacts.json " ) 5. Trying it out Given a contact

本文内容来源于互联网,版权归原作者所有
查看原文