Skip to content

Commit e748ec2

Browse files
authored
Merge pull request #244 from onkar-kota/feat/json_to_csv
Added json_to_csv project (issue #150)
2 parents 6eee58b + 152f1c4 commit e748ec2

File tree

5 files changed

+140
-0
lines changed

5 files changed

+140
-0
lines changed

Diff for: Python Projects/json_to_csv/README.MD

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# json to csv convertor
2+
3+
## Introduction
4+
5+
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.
6+
7+
## Usage
8+
9+
### Prerequisites
10+
11+
Before using this script, ensure you have the following:
12+
13+
- Python installed on your system.
14+
- Required libraries: `csv`, `json`, `python`
15+
16+
### Running the Script
17+
18+
1. Place the json file you want to convert to csv file in the same directory as this script.
19+
20+
2. Replace the `input_file` variable with the name of your json file name with .json extention.
21+
22+
```python
23+
input_file = 'json_data.json'
24+
python json_to_csv_with_nested_dict.py
25+
```
26+
27+
### Information about .py file
28+
29+
1. `json_to_csv` function
30+
31+
- This function defines the JSON to CSV converter. It takes three arguments:
32+
- Args :
33+
- **json_data**: A JSON object or list of JSON objects.
34+
- **csv_file**: The path to the CSV file to write the data to.
35+
- **mapping**: A dictionary mapping JSON field names to CSV column headers.
36+
- Returns:
37+
- None
38+
39+
1. `flatten_json` function
40+
41+
- 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.
42+
43+
- Args :
44+
- **obj**: A nested JSON object.
45+
46+
- Returns:
47+
- A flattened JSON object.
48+
49+
### Output
50+
51+
The script will create a directory named **csv_data.csv** in the same location as the script. Within this directory.
52+
53+
![Alt text](image.png)
Binary file not shown.

Diff for: Python Projects/json_to_csv/image.png

9.72 KB
Loading

Diff for: Python Projects/json_to_csv/json_data.json

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
[
3+
{
4+
"name": "Test37",
5+
"status": "done",
6+
"slug": "test-375960",
7+
"date": "13-10-2023",
8+
"author": "unknown",
9+
"probability": "89%",
10+
"result": "70%",
11+
"final_status": "failed",
12+
"connected": {
13+
"run_again": "True",
14+
"next_test": "Test38",
15+
"next_test_status": "pending"
16+
}
17+
},
18+
{
19+
"name": "Test38",
20+
"status": "pending",
21+
"slug": "test-385960",
22+
"date": "13-10-2023",
23+
"author": "unknown",
24+
"probability": "80%",
25+
"result": "None",
26+
"final_status": "None"
27+
}
28+
]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import json
2+
import csv
3+
4+
def json_to_csv(json_data, csv_file, mapping=None):
5+
6+
if isinstance(json_data, list):
7+
# Flatten nested JSON structures.
8+
json_data = [flatten_json(obj) for obj in json_data]
9+
10+
# Get the column headers from the mapping or from the JSON data itself.
11+
column_headers = mapping or json_data[0].keys()
12+
13+
# Write the CSV file.
14+
with open(csv_file, "w", newline="") as f:
15+
writer = csv.writer(f)
16+
writer.writerow(column_headers)
17+
for row in json_data:
18+
# Convert nested values to strings.
19+
row_values = [str(row.get(column, "")) for column in column_headers]
20+
writer.writerow(row_values)
21+
22+
def flatten_json(obj):
23+
24+
flattened = {}
25+
for key, value in obj.items():
26+
if isinstance(value, dict):
27+
flattened.update(flatten_json(value))
28+
elif isinstance(value, list):
29+
for item in value:
30+
flattened["{}.{}".format(key, item)] = item
31+
else:
32+
flattened[key] = value
33+
return flattened
34+
35+
# sample mapping if needed
36+
mapping = {
37+
"name": "Name",
38+
"status": "Status",
39+
"date": "Date",
40+
"author": "Author",
41+
"probability": "Probability",
42+
"result": "Result",
43+
"final_status": "Final Status",
44+
"connected.run_again": "Run Again",
45+
"connected.next_test": "Next Test",
46+
"connected.next_test_status": "Next Test Status"
47+
}
48+
49+
50+
def main():
51+
# Load the JSON data.
52+
with open("json_data.json", "r") as json_file:
53+
json_data = json.load(json_file)
54+
55+
# Convert the JSON data to CSV format.
56+
json_to_csv(json_data, "csv_data.csv")
57+
58+
if __name__ == "__main__":
59+
main()

0 commit comments

Comments
 (0)