我正在尝试将JSON文件解析为CSV。我已经能够将JSON文件的头输出到CSV中,但我不知道如何将数据输入到文件中。
# Python program to convert
# JSON file to CSV
import json
import csv
# Opening JSON file and loading the data
# into the variable data
with open('test1.json') as json_file:
data = json.load(json_file)
for i in range(len(data)):
training_data = data[i]['profile']
# now we will open a file for writing
data_file = open('data_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
#type(training_data)
for profile in training_data:
if count == 0:
header = training_data.keys()
csv_writer.writerow(header)
count += 1
csv_writer.writerow(training_data.values())
data_file.close()
这是我试图解析的文件https://textdoc.co/OuphoV5saiwWYS8g
如果有人能帮我,我将永远感激
这样的东西对你有用吗?
import pandas as pd
df = pd.read_json(json_file)
df.to_csv('data_file.csv')
或者对于更复杂的嵌套json,您可能必须加载为字典并操作:
data = json.loads(json_str)
data_transformed = [i for i in data['data']]
df = pd.DataFrame(data_transformed )
df.to_csv('data_file.csv')