How to convert CSV to JSON using Python
CSV and JSON are most commonly used formats. JSON is usually used in REST API while CSV is usually used for data importing/exporting. With Python, we can easily convert CSV to JSON.
CSV and JSON are most commonly used formats. JSON is usually used in REST API while CSV is usually used for data importing/exporting. With Python, we can easily convert CSV to JSON.
Example we have a CSV file called fruit.csv
and the contents of it:
Time | Name | Quantity |
---|---|---|
4/5/2020 13:34 | Apples | 73 |
4/5/2020 3:41 | Cherries | 85 |
4/6/2020 12:46 | Pears | 14 |
4/8/2020 8:59 | Oranges | 52 |
4/10/2020 2:07 | Apples | 152 |
4/10/2020 18:10 | Bananas | 23 |
4/10/2020 2:40 | Strawberries | 98 |
The raw content of the CSV file:
Time,Name,Quantity
4/5/2020 13:34,Apples,73
4/5/2020 3:41,Cherries,85
4/6/2020 12:46,Pears,14
4/8/2020 8:59,Oranges,52
4/10/2020 2:07,Apples,152
4/10/2020 18:10,Bananas,23
4/10/2020 2:40,Strawberries,98
Let use Python to convert CSV to JSON
import csv
import json
json_content = []
with open('fruit.csv', encoding='utf8', newline='') as f:
reader = csv.DictReader(f)
for row in reader:
json_content.append(row)
# Write json to file
with open('fruit.json', 'w', encoding='utf8') as f:
json.dump(json_content, f, indent=4)
The JSON content is:
[
{
Time: "4/5/2020 13:34",
Name: "Apples",
Quantity: "73",
},
{
Time: "4/5/2020 3:41",
Name: "Cherries",
Quantity: "85",
},
{
Time: "4/6/2020 12:46",
Name: "Pears",
Quantity: "14",
},
{
Time: "4/8/2020 8:59",
Name: "Oranges",
Quantity: "52",
},
{
Time: "4/10/2020 2:07",
Name: "Apples",
Quantity: "152",
},
{
Time: "4/10/2020 18:10",
Name: "Bananas",
Quantity: "23",
},
{
Time: "4/10/2020 2:40",
Name: "Strawberries",
Quantity: "98",
},
];
Last modified October 6, 2020