I have a deeply nested json representing a python dict. The data represents files on a…
- User
I have a deeply nested json representing a python dict. The data represents files on a harddrive in the following format: {"dir1": {"sub dir 1": {"filename": {"bytes": 123, "hash": "AC3"}, "file2": {"bytes": 120, "hash": "156"} }, {"sub dir 2": {"file 3": {"bytes": 420, "hash": "82D"}} }}
I want a python script that reads this deeply nested json and produces a list of files and directories in CSV format like this: path, bytes, hash dir1/sub dir 1/filename,123,AC3 dir1/sub dir 1/file2,120,156 dir1/sub dir 2/file 3,420,82D
Note that the files themselfs are also dicts inside the deeply nested dict
Assistant
Here is a Python script that does what you described:
import json import csv data = {"dir1": {"sub dir 1": {"filename": {"bytes": 123, "hash": "AC3"}, "file2": {"bytes": 120, "hash": "156"} }, "sub dir 2": {"file 3": {"bytes": 420, "hash": "82D"}} }} rows = [] for dir_name, dir_value in data.items(): for sub_dir_name, sub_dir_value in dir_value.items(): for file_name, file_value in sub_dir_value.items(): path = f"{dir_name}/{sub_dir_name}/{file_name}" rows.append([path, file_value["bytes"], file_value["hash"]]) with open('output.csv', 'w') as f: writer = csv.writer(f) writer.writerow(["path", "bytes", "hash"]) writer.writerows(rows)This traverses the nested dictionaries to build up the path strings. It extracts the bytes and hash values into lists, then writes the rows out to a CSV file with headers.
The output CSV would contain:
path, bytes, hash dir1/sub dir 1/filename,123,AC3 dir1/sub dir 1/file2,120,156 dir1/sub dir 2/file 3,420,82DLet me know if you have any other questions!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.