How can I convert JSON to CSV?

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

    Alec's answer is great, but it doesn't work in the case where there are multiple levels of nesting. Here's a modified version that supports multiple levels of nesting. It also makes the header names a bit nicer if the nested object already specifies its own key (e.g. Firebase Analytics / BigTable / BigQuery data):

    """Converts JSON with nested fields into a flattened CSV file.
    """
    
    import sys
    import json
    import csv
    import os
    
    import jsonlines
    
    from orderedset import OrderedSet
    
    # from https://stackoverflow.com/a/28246154/473201
    def flattenjson( b, prefix='', delim='/', val=None ):
      if val is None:
        val = {}
    
      if isinstance( b, dict ):
        for j in b.keys():
          flattenjson(b[j], prefix + delim + j, delim, val)
      elif isinstance( b, list ):
        get = b
        for j in range(len(get)):
          key = str(j)
    
          # If the nested data contains its own key, use that as the header instead.
          if isinstance( get[j], dict ):
            if 'key' in get[j]:
              key = get[j]['key']
    
          flattenjson(get[j], prefix + delim + key, delim, val)
      else:
        val[prefix] = b
    
      return val
    
    def main(argv):
      if len(argv) < 2:
        raise Error('Please specify a JSON file to parse')
    
      print "Loading and Flattening..."
      filename = argv[1]
      allRows = []
      fieldnames = OrderedSet()
      with jsonlines.open(filename) as reader:
        for obj in reader:
          # print 'orig:\n'
          # print obj
          flattened = flattenjson(obj)
          #print 'keys: %s' % flattened.keys()
          # print 'flattened:\n'
          # print flattened
          fieldnames.update(flattened.keys())
          allRows.append(flattened)
    
      print "Exporting to CSV..."
      outfilename = filename + '.csv'
      count = 0
      with open(outfilename, 'w') as file:
        csvwriter = csv.DictWriter(file, fieldnames=fieldnames)
        csvwriter.writeheader()
        for obj in allRows:
          # print 'allRows:\n'
          # print obj
          csvwriter.writerow(obj)
          count += 1
    
      print "Wrote %d rows" % count
    
    
    
    if __name__ == '__main__':
      main(sys.argv)
    

提交回复
热议问题