Skip to content

Commit f8af0b5

Browse files
authored
Merge pull request #189 from onkar-kota/feat/json_to_csv
Added json_to_csv file (issue #188)
2 parents e435a3f + 23c47da commit f8af0b5

File tree

6 files changed

+149
-0
lines changed

6 files changed

+149
-0
lines changed

Json_to_csv convertor/README.MD

Lines changed: 53 additions & 0 deletions
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)

Json_to_csv convertor/image.png

9.72 KB
Loading

Json_to_csv convertor/json_to_csv.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import json
2+
import csv
3+
4+
def json_to_csv(input_json_file, output_csv_file):
5+
try:
6+
# Read JSON data from input file using utf-8-sig encoding to handle BOM
7+
with open(input_json_file, 'r', encoding='utf-8-sig') as json_file:
8+
data = json.load(json_file)
9+
10+
# Get the keys from the first JSON object to use as column headers
11+
headers = list(data[0].keys())
12+
13+
# Write CSV data to output file
14+
with open(output_csv_file, 'w', newline='') as csv_file:
15+
writer = csv.DictWriter(csv_file, fieldnames=headers)
16+
17+
# Write column headers to CSV file
18+
writer.writeheader()
19+
20+
# Write JSON data to CSV file
21+
for row in data:
22+
writer.writerow(row)
23+
24+
print(f"Conversion from JSON to CSV completed successfully. CSV file saved as {output_csv_file}")
25+
26+
except Exception as e:
27+
print(f"An error occurred: {str(e)}")
28+
29+
# Example usage
30+
input_json_file = 'path_to_input.json'
31+
output_csv_file = 'path_to_output.csv'
32+
33+
json_to_csv(input_json_file, output_csv_file)
Lines changed: 59 additions & 0 deletions
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()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
json
2+
csv

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
- [Table of Contents](#table-of-contents)
44
- [Python Scripts](#python-scripts)
55
- [Contributing](#contributing)
6+
- [Adding a New Script](#adding-a-new-script)
67
- [List of Scripts in Repo](#list-of-scripts-in-repo)
78
- [Wall of Contributors](#wall-of-contributors)
89

@@ -67,6 +68,7 @@ More information on contributing and the general code of conduct for discussion
6768
| JSON to CSV 1 | [JSON to CSV](https://github.com/DhanushNehru/Python-Scripts/tree/master/JSON2CSV) | Convert JSON to CSV files. |
6869
| JSON to CSV 2 | [JSON to CSV](https://github.com/DhanushNehru/Python-Scripts/tree/master/Json_2_csv) | Converts a JSON file to a CSV file. |
6970
| JSON to YAML converter | [JSON to YAML converter](https://github.com/DhanushNehru/Python-Scripts/tree/master/json_2_yaml) | Converts JSON file to YAML files. A sample JSON is included for testing. |
71+
| JSON to CSV converter | [JSON to CSV converter](https://github.com/DhanushNehru/Python-Scripts/tree/master/Json_to_csv_convertor) | Converts JSON file to CSV files. It can convert nested json files as well. A sample JSON is included for testing.
7072
| Keylogger | [Keylogger](https://github.com/DhanushNehru/Python-Scripts/tree/master/Keylogger) | Keylogger that can track your keystrokes, clipboard text, take screenshots at regular intervals, and records audio. |
7173
| Keyword - Retweeting | [Keyword - Retweeting](https://github.com/DhanushNehru/Python-Scripts/tree/master/Keyword-retweet-twitter-bot) | Find latest tweets containing given keywords and then retweet them. |
7274
| LinkedIn Bot | [LinkedIn Bot](https://github.com/DhanushNehru/Python-Scripts/tree/master/LinkedIn_Bot) | Automates the process of searching for public profiles on LinkedIn and exporting the data to an Excel sheet. |

0 commit comments

Comments
 (0)