# Title: ConvertJson2Csl.py # Author: Rubinigg Davide # Contributor: Rubinigg Michael # Abstract: Converts JSON files of any structure to CSV files based on user input # Version 1.0 # Release date: 2023-06-19 # Place: Graz, Austria, EU # Company: dr Mag. rer. nat. Michael Rubinigg # Programming Language: Python 3.11 # Rights: Creative Commons Attribution 4.0 (CC-BY) import json import pandas as pd from tkinter import filedialog as fd, simpledialog import tkinter as tk from pathlib import Path def extract_translations(data, path, translations_list): if isinstance(data, dict): for key, value in data.items(): new_path = path + [key] extract_translations(value, new_path, translations_list) elif isinstance(data, str): translation = path + [data] translations_list.append(translation) else: translation = path + [data] translations_list.append(translation) def get_string_input(): # Create the Tkinter window window = tk.Tk() window.withdraw() # Prompt the user for string input user_input = simpledialog.askstring("String Input", "Enter a string:") # Close the Tkinter window window.destroy() # Return the user input return user_input def get_data_by_path(data, root_path: str): root_path = root_path.split(",") root_object = data for key in root_path: if key in root_object: root_object = root_object[key] else: raise KeyError(f"Key '{key}' not found in the JSON data.") return root_object def extract(file_path: Path, json_path: str, output_path: Path): with open(file_path, encoding='utf-8') as inputfile: data = json.loads(inputfile.read()) data = get_data_by_path(data, json_path) translations_list = [] extract_translations(data, [], translations_list) data_frame = pd.DataFrame(translations_list) data_frame.to_csv(output_path, index=False) def main(): input_path = Path(fd.askopenfilename()) root_path = get_string_input() output_path = Path(fd.asksaveasfilename(defaultextension=".csv", filetypes=[("CSV Files", "*.csv")])) extract(input_path, root_path, output_path) if __name__ == '__main__': main()