我正在尝试使用Python 2.7将JSON文件转换为CSV。 JSON文件包含多个字段,包括URL和请求的描述。我可以将URL和Description以外的所有其他字段加载到CSV。
下面是我的代码:
import json
import csv
import os
import codecs
import sys
reload(sys)
sys.setdefaultencoding('utf8')
file_dir = os.path.normpath('/home/ppande/jobs/staging/')
exp_dir = os.path.normpath('/home/ppande/jobs/CSV/')
exp_file_name = 'emails.csv'
exp_path = os.path.join(exp_dir, exp_file_name)
my_dict_list =[]
for f in os.listdir(file_dir):
if f.endswith('.json') and f.startswith('emails_'):
file_path = os.path.join(file_dir, f)
data = open(file_path, 'r')
for line in data:
my_dict = {}
parsed_data = json.loads(line)
my_dict["REQUEST_ID"] = parsed_data["requestId"]
my_dict["SUCCESS"] = parsed_data["success"]
for result in parsed_data["result"]:
my_dict["RESULT_ID"] = result["id"]
my_dict["NAME"] = result["name"]
#my_dict["DESCRIPTION"] = result["description"]
#my_dict["URL"] = result["url"]
my_dict["CREATED_AT"] = result["createdAt"]
my_dict["UPDATED_AT"] = result["updatedAt"]
my_dict_list.append(my_dict)
csv_columns = ["REQUEST_ID","SUCCESS","RESULT_ID","NAME","CREATED_AT","UPDATED_AT"]
with open(exp_path,'wb') as csvfile:
xz = csv.DictWriter(csvfile,fieldnames=csv_columns)
headers = {}
for n in xz.fieldnames:
headers[n] = n
xz.writerow(headers)
for data in my_dict_list:
#if isinstance(data, str):
#data = unicode(data, "utf-8")
xz.writerow(data)
以下是URL和Description字段在源文件中的样子:
“ url”:“ https://app-abc.com/#EMXXXXX1”
“描述”:“”(大多数情况下为空)