How can I convert JSON to CSV?

前端 未结 26 1668
余生分开走
余生分开走 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:49

    Modified Alec McGail's answer to support JSON with lists inside

        def flattenjson(self, mp, delim="|"):
                ret = []
                if isinstance(mp, dict):
                        for k in mp.keys():
                                csvs = self.flattenjson(mp[k], delim)
                                for csv in csvs:
                                        ret.append(k + delim + csv)
                elif isinstance(mp, list):
                        for k in mp:
                                csvs = self.flattenjson(k, delim)
                                for csv in csvs:
                                        ret.append(csv)
                else:
                        ret.append(mp)
    
                return ret
    

    Thanks!

提交回复
热议问题