How can I convert JSON to CSV?

前端 未结 26 1666
余生分开走
余生分开走 2020-11-21 22:32

I have a JSON file I want to convert to a CSV file. How can I do this with Python?

I tried:

import json
import c         


        
26条回答
  •  故里飘歌
    2020-11-21 22:58

    It'll be easy to use csv.DictWriter(),the detailed implementation can be like this:

    def read_json(filename):
        return json.loads(open(filename).read())
    def write_csv(data,filename):
        with open(filename, 'w+') as outf:
            writer = csv.DictWriter(outf, data[0].keys())
            writer.writeheader()
            for row in data:
                writer.writerow(row)
    # implement
    write_csv(read_json('test.json'), 'output.csv')
    

    Note that this assumes that all of your JSON objects have the same fields.

    Here is the reference which may help you.

提交回复
热议问题