Ideas:
Convert multiple JSON elements into groups, then use Python's CSV and JSON modules to handle them.
Sample format:
[{ "description": null, "image": { "Image_size": 20, "os_family": "CentOS", "platform": "Linux", "Image_name": "Tomcat-v1.7-base image-v2", "provider": "self", "image_id": "xxxxxxxxx", "Processor_Type": "64bit", "Ui_type": "Tui" }, " Instance_name ": " faint ", " transition_status ": " ", " sub_ Code ": 0, " Lastest_snapshot_time ": " ", " cpu_topology ": ", " memory_current ": 4096, " Vxnets ": [], "StatuS ": " ceased ", " Vcpus_current ": 2, " instance_id ": "I-xxxxxx", "Instance_type": "c2m4", "Instance_class": 0, "dns_aliases": [], "Create_time": " 2015-03-17t02:06:57z ", " owner ": " xxxxxxxxxxxx ", " Status_ Time ": " 2015-03-17t04:14:49z ", " Alarm_status ": " "  }]
How to use:
Python json2csv.py/tmp/test.json/tmp/test.csv instance_id,instance_name,create_time,vcpus_current,memory_current , Status,status_time image
The processing results are as follows:
i-xxxxxx,xxxxxx,2015-03-17t02:18:34z,2,4096,ceased,2015-03-17t04:22:04z,tui,64bit,xxxxxxxxxxxxxxxxxx,20, Xxxxxxxx,linux,centos,self
Directly on the code
#!/usr/bin/env python# -*- coding: utf-8 -*-import jsonimport csvimport fcntlimport time import sys reload (SYS) sys.setdefaultencoding (' UTF8 ') # read file handle F_read = open (Sys.argv[1]) data = json.load (f_read) f_read.close () # Write file handle F_write=open (sys.argv[2], ' wb+ ') f=csv.writer (f_write) # file lock Fcntl.flock (f_write,fcntl. LOCK_EX) # read the next variable del sys.argv[0]del sys.argv[0]del sys.argv[0]# level store the key to be read to the list if len (SYS.ARGV) >0:m1=sys.argv[0].split (', ') Del sys.argv[0]else:m1=[]if len (SYS.ARGV) >0:m2= Sys.argv[0].split (', ') Del sys.argv[0]else:m2=[]if len (SYS.ARGV) >0:m3=sys.argv[0].split (', ') del sys.argv[0]else:m3=[]# Store all keyall_keys=m1+m2+m3# printed headers to be read #print ', '. Join (All_keys) # F.writerow (All_keys) # print elements individually for item in data:x=[]for z in all_keys:if Z in m1:x+=[str (Item[z]). Encode (' Utf-8', ' Ignore ')]if z in m2:x+=item[z].values () #print ', '. Join (x) f.writerow (x) fcntl.flock (F_write,fcntl. Lock_un) F_write.close ()
This article is from the "in Hio Open source" blog, please be sure to keep this source http://wangxiaoyu.blog.51cto.com/922065/1655783
JSON-to-CSV conversion