从文件夹中读取JSON文件并将其存储到CSV文件中

时间:2019-06-26 13:30:54

标签: python export-to-csv json2csv

我在一个文件夹中有大约1000个JSON文件,我想将所有这些文件转换为CSV格式。 JSON文件的示例如下。

{"Reviews": 
   [
    {"Title": "Don't give up on your NOOK HD just yet - make it a Lean Mean Jellybean with OS 4.2.2", 
    "Author": "DC10", 
    "ReviewID": "ROX6OFU4UAOK1", 
    "Overall": "5.0", 
    "Content": "Hi Folks, ", 
    "Date": "February 18, 2013"}, 

    {"Title": "freezing problem",
    "Author": "joseph",
    "ReviewID": "R1QVAPUULQZ57B",
    "Overall": "3.0", 
    "Content": "I am still setting it up the way I want it I havve downloaded anything to it yet and it freezes horribly. All in all tho I love this device.", 
    "Date": "September 11, 2013"}
    ], 
"ProductInfo": {"Price": "$229.00", "Features": "NOOK HD 7\" 16GB Tablet", "Name": "NOOK HD 7\" 16GB Tablet", 
"ImgURL": "http://ecx.images-amazon.com/images/I/41jpVvVz41L._SY300_.jpg", 
"ProductID": "1400501520"}}

2 个答案:

答案 0 :(得分:0)

示例:将json转换为csv

进口:

import json
import csv

一些json:D

data_json = {
    "employee_details": [{
            "nom": "Bobby",
            "age": "19",
        }]
}

和一些代码

employee_data = data_json['employee_details']

# open a file for writing
employ_data = open('EmployData.csv', 'w')

# create the csv writer object
csvwriter = csv.writer(employ_data)

count = 0
for employee in employee_data:
      if count == 0:
             header = employee.keys()
             csvwriter.writerow(header)
             count += 1
      csvwriter.writerow(employee.values())

employ_data.close()

您将在脚本旁边找到文件EmployeeData.csv

答案 1 :(得分:0)

如果您愿意安装第三方模块,则可以使用pandas

for json_file in files:
    with open(json_file) as f:
        json_data = json.load(f)

    df = pandas.DataFrame.from_records(json_data)
    df.to_csv(json_file.rstrip('.json') + '.csv')