Skip to content

Added json_to_csv project (issue #150) #244

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions Python Projects/json_to_csv/README.MD
Original file line number Diff line number Diff line change
@@ -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)
Binary file not shown.
Binary file added Python Projects/json_to_csv/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
28 changes: 28 additions & 0 deletions Python Projects/json_to_csv/json_data.json
Original file line number Diff line number Diff line change
@@ -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"
}
]
59 changes: 59 additions & 0 deletions Python Projects/json_to_csv/json_to_csv_with_nested_dict.py
Original file line number Diff line number Diff line change
@@ -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()