CSV (Comma-Separated Values) files are widely used for storing tabular data. Converting CSV files into JSON format is essential for working with APIs, databases, and JavaScript applications.
Ensure your CSV file is properly formatted with column headers. Example:
name,age,city John,25,New York Alice,30,Los Angeles Bob,28,Chicago
You can use an online tool to convert CSV to JSON by uploading the file and downloading the JSON output.
If you prefer coding, use Python to convert CSV to JSON. Below is a simple script:
import csv import json csv_file = "data.csv" json_file = "data.json" data = [] with open(csv_file, "r") as file: reader = csv.DictReader(file) for row in reader: data.append(row) with open(json_file, "w") as file: json.dump(data, file, indent=4) print("CSV file converted to JSON successfully!")
You can also use JavaScript to convert CSV to JSON:
function csvToJson(csv) { const lines = csv.split("\n"); const headers = lines[0].split(","); const result = []; for (let i = 1; i < lines.length; i++) { let obj = {}; let row = lines[i].split(","); headers.forEach((header, index) => { obj[header] = row[index]; }); result.push(obj); } return JSON.stringify(result, null, 4); } const csvData = "name,age,city\nJohn,25,New York\nAlice,30,Los Angeles\nBob,28,Chicago"; console.log(csvToJson(csvData));
The converted JSON will look like this:
[ { "name": "John", "age": "25", "city": "New York" }, { "name": "Alice", "age": "30", "city": "Los Angeles" }, { "name": "Bob", "age": "28", "city": "Chicago" } ]
By following these steps, you can easily convert CSV files into JSON using online tools, Python, or JavaScript. This conversion is useful for data processing and web applications.