Convert JSON to CSV using Python (Idle)

前端 未结 4 1436
旧巷少年郎
旧巷少年郎 2021-02-14 06:31

I have a JSON file of Latitude/Longitude that I want to covert to a CSV file. I want to do this using Python. I have read/tried all other stackoverflow and google search results

4条回答
  •  逝去的感伤
    2021-02-14 07:17

    I would use a csv.DictWriter, since you're dealing with dicts, which is exactly the case DictWriter is there for.

    rows = json.loads(x)
    with open('test.csv', 'wb+') as f:
        dict_writer = csv.DictWriter(f, fieldnames=['longitude', 'latitude'])
        dict_writer.writeheader()
        dict_writer.writerows(rows)
    


    Edit:
    Since the .writeheader() method was only added in 2.7, you can use something like this on older versions:

    rows = json.loads(x)
    fieldnames = ['longitude', 'latitude']
    with open('test.csv', 'wb+') as f:
        dict_writer = csv.DictWriter(f, fieldnames=fieldnames)
        dict_writer.writerow(dict(zip(fieldnames, fieldnames)))
        dict_writer.writerows(rows)
    

提交回复
热议问题