![](/img/trans.png)
[英]how to convert all json files of directory to text files in python?
[英]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
打開這些文件並組合“Highlights”和“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')
Output:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.