diff --git a/Python Projects/json_to_csv/README.MD b/Python Projects/json_to_csv/README.MD new file mode 100644 index 00000000..3fa8ddf2 --- /dev/null +++ b/Python Projects/json_to_csv/README.MD @@ -0,0 +1,53 @@ +# json to csv convertor + +## Introduction + +This Python script allows you to convert json file to csv file and save them to a specified directory. It uses json and csv library to process json files and do manupulations accordingly. + +## Usage + +### Prerequisites + +Before using this script, ensure you have the following: + +- Python installed on your system. +- Required libraries: `csv`, `json`, `python` + +### Running the Script + +1. Place the json file you want to convert to csv file in the same directory as this script. + +2. Replace the `input_file` variable with the name of your json file name with .json extention. + +```python +input_file = 'json_data.json' +python json_to_csv_with_nested_dict.py +``` + +### Information about .py file + +1. `json_to_csv` function + +- This function defines the JSON to CSV converter. It takes three arguments: +- Args : + - **json_data**: A JSON object or list of JSON objects. + - **csv_file**: The path to the CSV file to write the data to. + - **mapping**: A dictionary mapping JSON field names to CSV column headers. +- Returns: + - None + +1. `flatten_json` function + +- This function flattens the JSON data. It works by recursively iterating over the JSON object and converting any nested JSON objects into a single level of key-value pairs. + +- Args : + - **obj**: A nested JSON object. + +- Returns: + - A flattened JSON object. + +### Output + +The script will create a directory named **csv_data.csv** in the same location as the script. Within this directory. + +![Alt text](image.png) \ No newline at end of file diff --git a/Python Projects/json_to_csv/__pycache__/json_to_csv.cpython-311.pyc b/Python Projects/json_to_csv/__pycache__/json_to_csv.cpython-311.pyc new file mode 100644 index 00000000..bc2b7748 Binary files /dev/null and b/Python Projects/json_to_csv/__pycache__/json_to_csv.cpython-311.pyc differ diff --git a/Python Projects/json_to_csv/image.png b/Python Projects/json_to_csv/image.png new file mode 100644 index 00000000..ab11c439 Binary files /dev/null and b/Python Projects/json_to_csv/image.png differ diff --git a/Python Projects/json_to_csv/json_data.json b/Python Projects/json_to_csv/json_data.json new file mode 100644 index 00000000..e7c7e948 --- /dev/null +++ b/Python Projects/json_to_csv/json_data.json @@ -0,0 +1,28 @@ + +[ + { + "name": "Test37", + "status": "done", + "slug": "test-375960", + "date": "13-10-2023", + "author": "unknown", + "probability": "89%", + "result": "70%", + "final_status": "failed", + "connected": { + "run_again": "True", + "next_test": "Test38", + "next_test_status": "pending" + } + }, + { + "name": "Test38", + "status": "pending", + "slug": "test-385960", + "date": "13-10-2023", + "author": "unknown", + "probability": "80%", + "result": "None", + "final_status": "None" + } +] \ No newline at end of file diff --git a/Python Projects/json_to_csv/json_to_csv_with_nested_dict.py b/Python Projects/json_to_csv/json_to_csv_with_nested_dict.py new file mode 100644 index 00000000..bcb23c69 --- /dev/null +++ b/Python Projects/json_to_csv/json_to_csv_with_nested_dict.py @@ -0,0 +1,59 @@ +import json +import csv + +def json_to_csv(json_data, csv_file, mapping=None): + + if isinstance(json_data, list): + # Flatten nested JSON structures. + json_data = [flatten_json(obj) for obj in json_data] + + # Get the column headers from the mapping or from the JSON data itself. + column_headers = mapping or json_data[0].keys() + + # Write the CSV file. + with open(csv_file, "w", newline="") as f: + writer = csv.writer(f) + writer.writerow(column_headers) + for row in json_data: + # Convert nested values to strings. + row_values = [str(row.get(column, "")) for column in column_headers] + writer.writerow(row_values) + +def flatten_json(obj): + + flattened = {} + for key, value in obj.items(): + if isinstance(value, dict): + flattened.update(flatten_json(value)) + elif isinstance(value, list): + for item in value: + flattened["{}.{}".format(key, item)] = item + else: + flattened[key] = value + return flattened + +# sample mapping if needed +mapping = { + "name": "Name", + "status": "Status", + "date": "Date", + "author": "Author", + "probability": "Probability", + "result": "Result", + "final_status": "Final Status", + "connected.run_again": "Run Again", + "connected.next_test": "Next Test", + "connected.next_test_status": "Next Test Status" +} + + +def main(): + # Load the JSON data. + with open("json_data.json", "r") as json_file: + json_data = json.load(json_file) + + # Convert the JSON data to CSV format. + json_to_csv(json_data, "csv_data.csv") + +if __name__ == "__main__": + main()