将目录中所有 .json 文件的 JSON 转换为 XLSX
Convert JSON into XLSX of all .json files in directory
面临读取与程序可执行文件位于同一目录下的所有json文件的问题,选择这些文件中的某些元素并将它们保存在一个Excel文件中.
例如,我有很多 JSON 个文件,例如:
第一个文件
{"General":{"Code":"AAIC-PB","Type":"Preferred Share","Name":"Arlington Asset Investment Corp"}, "Highlights":{"MarketCapitalization":211528800,"MarketCapitalizationMln":211.5288}}
第二个文件
{"General":{"Code":"A","Type":"Common Stock","Name":"Agilent Technologies"}, "Highlights":{"MarketCapitalization":567456,"MarketCapitalizationMln":222.567}}
我想获取特定键及其值并将其放入 excel。例如,从 General 中获取 CODE,从 Highlights 中获取 MarketCapitalization所以最后肯定是这样的:
本人是python新手,求懂的人帮忙。
谢谢!
这应该适合您,使用 glob
查找目录中的所有 json 文件,然后对每个文件使用 json
打开这些文件并组合“亮点” " 和 "General" 键并将所有生成的词典添加到列表中,然后保存到 csv
import csv
import json
from glob import glob
# function to open json files
def read_json(path):
with open(path, 'r') as file:
return json.load(file)
# function to save csv files
def write_csv(data, path):
with open(path, 'w') as file:
# get all the keys
fieldnames = set().union(*data)
writer = csv.DictWriter(file, fieldnames=fieldnames, lineterminator='\n')
writer.writeheader()
writer.writerows(data)
# use glob to find all the *.json files in the folder named json_dir
json_files = glob('./json_dir/*.json')
rows = []
for json_file in json_files:
# read the json file
json_data = read_json(json_file)
# combine General and Highlights into the same dictionary
rows.append({**json_data['General'], **json_data['Highlights']})
# write the csv to json_data.csv
write_csv(rows, './json_data.csv')
输出:
面临读取与程序可执行文件位于同一目录下的所有json文件的问题,选择这些文件中的某些元素并将它们保存在一个Excel文件中.
例如,我有很多 JSON 个文件,例如:
第一个文件
{"General":{"Code":"AAIC-PB","Type":"Preferred Share","Name":"Arlington Asset Investment Corp"}, "Highlights":{"MarketCapitalization":211528800,"MarketCapitalizationMln":211.5288}}
第二个文件
{"General":{"Code":"A","Type":"Common Stock","Name":"Agilent Technologies"}, "Highlights":{"MarketCapitalization":567456,"MarketCapitalizationMln":222.567}}
我想获取特定键及其值并将其放入 excel。例如,从 General 中获取 CODE,从 Highlights 中获取 MarketCapitalization所以最后肯定是这样的:
本人是python新手,求懂的人帮忙。 谢谢!
这应该适合您,使用 glob
查找目录中的所有 json 文件,然后对每个文件使用 json
打开这些文件并组合“亮点” " 和 "General" 键并将所有生成的词典添加到列表中,然后保存到 csv
import csv
import json
from glob import glob
# function to open json files
def read_json(path):
with open(path, 'r') as file:
return json.load(file)
# function to save csv files
def write_csv(data, path):
with open(path, 'w') as file:
# get all the keys
fieldnames = set().union(*data)
writer = csv.DictWriter(file, fieldnames=fieldnames, lineterminator='\n')
writer.writeheader()
writer.writerows(data)
# use glob to find all the *.json files in the folder named json_dir
json_files = glob('./json_dir/*.json')
rows = []
for json_file in json_files:
# read the json file
json_data = read_json(json_file)
# combine General and Highlights into the same dictionary
rows.append({**json_data['General'], **json_data['Highlights']})
# write the csv to json_data.csv
write_csv(rows, './json_data.csv')
输出: