csv to json with python, json in rows

前端 未结 2 1840
自闭症患者
自闭症患者 2021-01-15 01:11

I would like to covert a CSV to a set of JSON objects with Python, formatted in rows.

I tried this script below, put together from a couple SO answers, but this form

2条回答
  •  梦毁少年i
    2021-01-15 01:22

    import csv
    import json
    
    CSV_PATH = 'file.csv'
    JSON_PATH = 'demo.json'
    
    with open(CSV_PATH, 'r') as csv_file:
        reader = csv.DictReader(csv_file)
        with open(JSON_PATH, 'w') as json_file:
            for row in reader:
                json_file.write(json.dumps(row) + '\n')
    

    str(row) gives the wrong kind of quotes, don't use it. You won't be able to read the file with json.

提交回复
热议问题