简体   繁体   English

将JSON转换成目录下all.json文件的XLSX

[英]Convert JSON into XLSX of all .json files in directory

Faced with the problem of reading all json files which are located in the same directory as the executable file of the program, selecting certain elements in these files and saving them in one Excel file.面对读取与程序可执行文件位于同一目录的所有json文件的问题,选择这些文件中的某些元素并将它们保存在一个Excel文件中。

For example, I have a lot of JSON files like:例如,我有很多 JSON 文件,例如:

First file第一个文件

{"General":{"Code":"AAIC-PB","Type":"Preferred Share","Name":"Arlington Asset Investment Corp"}, "Highlights":{"MarketCapitalization":211528800,"MarketCapitalizationMln":211.5288}}

Second file第二个文件

{"General":{"Code":"A","Type":"Common Stock","Name":"Agilent Technologies"}, "Highlights":{"MarketCapitalization":567456,"MarketCapitalizationMln":222.567}}

I wanna take specific key and its' value and put it into excel.我想获取特定的密钥及其值并将其放入 excel。 For example take CODE from General and MarketCapitalization from Highlights so it must be smth like this in the end:例如,从General中获取CODE ,从Highlights中获取MarketCapitalization ,所以它最终必须是这样的:

在此处输入图像描述

I am new to python, so I ask for help from those who knows.我是 python 的新手,所以我向知道的人寻求帮助。 Thank you!谢谢!

This should work for you, use glob to find all the json files in a directory, then for each file use json to open those files and combine the "Highlights" and "General" keys and add all the resulting dictionaries to a list, then save to csv这应该对你有用,使用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: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM