How can I convert JSON to CSV?

前端 未结 26 2088
余生分开走
余生分开走 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 23:07

    This works relatively well. It flattens the json to write it to a csv file. Nested elements are managed :)

    That's for python 3

    import json
    
    o = json.loads('your json string') # Be careful, o must be a list, each of its objects will make a line of the csv.
    
    def flatten(o, k='/'):
        global l, c_line
        if isinstance(o, dict):
            for key, value in o.items():
                flatten(value, k + '/' + key)
        elif isinstance(o, list):
            for ov in o:
                flatten(ov, '')
        elif isinstance(o, str):
            o = o.replace('\r',' ').replace('\n',' ').replace(';', ',')
            if not k in l:
                l[k]={}
            l[k][c_line]=o
    
    def render_csv(l):
        ftime = True
    
        for i in range(100): #len(l[list(l.keys())[0]])
            for k in l:
                if ftime :
                    print('%s;' % k, end='')
                    continue
                v = l[k]
                try:
                    print('%s;' % v[i], end='')
                except:
                    print(';', end='')
            print()
            ftime = False
            i = 0
    
    def json_to_csv(object_list):
        global l, c_line
        l = {}
        c_line = 0
        for ov in object_list : # Assumes json is a list of objects
            flatten(ov)
            c_line += 1
        render_csv(l)
    
    json_to_csv(o)
    

    enjoy.

提交回复
热议问题