Table of Contents

    CSV and JSON Basics

    Chapter 17.7

    CSV and JSON Basics

    Learn the basics of CSV and JSON files, why they are used in programming, how they store structured data, how they are different from each other, and how they are used in real-world applications such as student records, configuration files, APIs, reports, and data exchange.

    Introduction

    In programming, data is often stored in files so that it can be saved, shared, processed, and reused later. Two very common file formats used for storing and exchanging data are CSV and JSON.

    CSV stands for Comma-Separated Values. It is commonly used to store tabular data such as student records, employee lists, product details, marksheets, attendance records, and spreadsheet-like data.

    JSON stands for JavaScript Object Notation. It is commonly used to store structured data in key-value format. JSON is widely used in web applications, APIs, configuration files, application settings, and data exchange between systems.

    Both CSV and JSON are text-based file formats. This means they can usually be opened and viewed in a text editor. However, their structure and use cases are different.

    "CSV is best for simple table-like data, while JSON is best for structured key-value data."

    Simple Definition of CSV and JSON

    CSV and JSON are file formats used to store data in a structured way. They help programs save data in files and read that data again later.

    BASIC IDEA
    CSV = Rows and Columns   |   JSON = Keys and Values

    In simple words:

    • CSV stores data like a table.
    • JSON stores data like objects or dictionaries.
    • CSV is simple and compact for flat records.
    • JSON is flexible and supports nested data.
    • Both are text-based and commonly used in programming.
    • Both can be read, written, and processed by programs.
    Important: CSV and JSON are not programming languages. They are data formats used to store and exchange information.

    Prerequisites

    Before learning CSV and JSON, students should understand some basic programming and file handling concepts.

    Prerequisite Topic Why It Is Needed
    Files and Folders To understand where CSV and JSON files are stored.
    Reading Files To load CSV or JSON data into a program.
    Writing Files To save CSV or JSON data from a program.
    File Paths To locate CSV and JSON files correctly.
    Strings CSV and JSON files are stored as text.
    Arrays / Lists To store multiple records from CSV or JSON files.
    Objects / Dictionaries To understand JSON key-value structure.
    Loops To process multiple rows or records.

    What is CSV?

    CSV stands for Comma-Separated Values. A CSV file stores data in plain text format, where each line usually represents one record and each value is separated by a comma.

    CSV is commonly used for storing tabular data. If you have data that looks like a table with rows and columns, CSV is often a simple and useful format.

    For example, student data can be stored in a CSV file with columns such as roll number, name, course, and marks.

    CSV as a Table

    Think of CSV as a simple table stored in a text file. Each row is a record, and each comma separates one column value from another.

    Example of CSV File

    Below is an example of a CSV file storing student records:

    
    rollNumber,name,course,marks
    101,Rahul,Programming Fundamentals,85
    102,Ayesha,Programming Fundamentals,92
    103,John,Programming Fundamentals,76
    104,Priya,Programming Fundamentals,88
    

    In this example:

    • The first line is the header row.
    • The header row defines column names.
    • Each following line represents one student record.
    • Each value is separated by a comma.
    CSV Part Meaning Example
    Header Row Defines column names. rollNumber,name,course,marks
    Data Row Represents one record. 101,Rahul,Programming Fundamentals,85
    Comma Separates values. Rahul,Programming Fundamentals
    Line Break Separates records. Each student appears on a new line.

    Structure of CSV

    A CSV file usually follows a simple structure:

    CSV STRUCTURE
    Header Row + Data Rows

    Basic CSV rules:

    • Each row is written on a new line.
    • Values are separated by commas.
    • The first row often contains column names.
    • All rows should usually follow the same column order.
    • CSV files are commonly saved with the .csv extension.

    What is JSON?

    JSON stands for JavaScript Object Notation. JSON is a text-based data format that stores data using key-value pairs.

    JSON is commonly used when data has a more structured form. It can store objects, arrays, nested objects, numbers, strings, booleans, and null values. This makes JSON more flexible than CSV for complex data.

    JSON is widely used in modern web development, APIs, configuration files, mobile apps, backend systems, and data exchange between applications.

    JSON as an Object

    Think of JSON as a structured object written in text form. Each value has a name, called a key, which makes the data easy for programs to understand.

    Example of JSON File

    Below is an example of a JSON file storing one student record:

    
    {
        "rollNumber": 101,
        "name": "Rahul",
        "course": "Programming Fundamentals",
        "marks": 85
    }
    

    In this example:

    • rollNumber, name, course, and marks are keys.
    • 101, Rahul, Programming Fundamentals, and 85 are values.
    • The data is enclosed inside curly braces.
    • Each key is usually written inside double quotes.

    JSON with Multiple Records

    JSON can also store multiple records using an array. An array is written using square brackets.

    
    [
        {
            "rollNumber": 101,
            "name": "Rahul",
            "course": "Programming Fundamentals",
            "marks": 85
        },
        {
            "rollNumber": 102,
            "name": "Ayesha",
            "course": "Programming Fundamentals",
            "marks": 92
        },
        {
            "rollNumber": 103,
            "name": "John",
            "course": "Programming Fundamentals",
            "marks": 76
        }
    ]
    

    This JSON file contains an array of student objects. Each object represents one student record.

    JSON Structure

    JSON has a clear structure based on keys and values. It supports different data types, which makes it flexible for storing complex information.

    JSON Element Meaning Example
    Object Collection of key-value pairs. { "name": "Rahul" }
    Key Name used to identify a value. "name"
    Value Data stored against a key. "Rahul"
    Array List of values or objects. [10, 20, 30]
    Nested Object Object inside another object. "address": { "city": "Kolkata" }
    String Text value. "Programming Fundamentals"
    Number Numeric value. 85
    Boolean true or false value. true
    null Empty or no value. null

    Nested JSON Example

    JSON can store nested data. This means one object can contain another object. This is useful when data has multiple levels.

    
    {
        "studentId": "S101",
        "name": "Rahul",
        "course": {
            "courseCode": "PL101",
            "courseName": "Programming Fundamentals",
            "durationInMonths": 6
        },
        "address": {
            "city": "Kolkata",
            "state": "West Bengal",
            "country": "India"
        },
        "result": {
            "marks": 85,
            "grade": "B",
            "status": "Passed"
        }
    }
    

    This example shows that JSON can represent complex data more naturally than CSV.

    CSV vs JSON

    CSV and JSON are both useful, but they are designed for different types of data. CSV is simpler for flat table data. JSON is better for structured and nested data.

    Basis CSV JSON
    Full Form Comma-Separated Values JavaScript Object Notation
    Data Style Rows and columns Key-value pairs
    Best For Simple table-like data Structured and nested data
    Human Readability Readable but less descriptive Readable and descriptive because of keys
    File Extension .csv .json
    Supports Nesting No natural nested structure Supports nested objects and arrays
    Data Size Usually smaller for flat records Can be larger because keys are repeated
    Common Use Spreadsheets, reports, records APIs, configuration, structured data exchange
    Parsing Needs splitting or CSV parser Needs JSON parser
    Example Data 101,Rahul,85 { "rollNumber": 101, "name": "Rahul", "marks": 85 }

    When Should You Use CSV?

    CSV is best when the data is simple and can be represented as rows and columns. It is commonly used when data needs to be opened in spreadsheet software or exchanged in a simple tabular format.

    Use CSV When

    • You need to store simple table data.
    • Each record has the same set of fields.
    • You want to open the file in spreadsheet software.
    • You want a compact format for flat records.
    • You are exporting reports or lists.
    • You are storing student marks, attendance, or product lists.
    • The data does not need nesting.
    • You want a beginner-friendly file format.

    When Should You Use JSON?

    JSON is best when the data has structure, relationships, or nested information. It is commonly used in web APIs, configuration files, and applications where data needs to be represented as objects.

    Use JSON When

    • You need to store structured data.
    • Data contains nested objects or arrays.
    • You are working with APIs.
    • You need key-value pairs.
    • You want data to be self-descriptive.
    • You are storing application configuration.
    • You need to represent complex entities such as student with address, course, and result.
    • You want a widely supported data exchange format.

    Real-World Example: Student Data in CSV

    Suppose we want to store basic student marks. CSV is a good choice because the data is simple and table-like.

    
    rollNumber,name,marks,grade
    101,Rahul,85,B
    102,Ayesha,92,A
    103,John,76,B
    104,Priya,88,B
    

    This format is easy to open in spreadsheet software and easy to process line by line.

    Real-World Example: Student Data in JSON

    Suppose we want to store a complete student profile with address, course, and result. JSON is a better choice because it supports nested structure.

    
    {
        "studentId": "S101",
        "name": "Rahul",
        "age": 20,
        "contactNumber": "9876543210",
        "address": {
            "city": "Kolkata",
            "state": "West Bengal",
            "country": "India"
        },
        "course": {
            "courseCode": "PL101",
            "courseName": "Programming Fundamentals",
            "durationInMonths": 6
        },
        "result": {
            "marks": 85,
            "grade": "B",
            "status": "Passed"
        }
    }
    

    This JSON structure clearly represents related data in a meaningful way.

    Java Example: Reading Simple CSV

    The following Java example reads a simple CSV file line by line and splits each row using commas.

    Prerequisites: To understand this example, you should know Java strings, arrays, loops, file reading, exception handling, and basic CSV structure.
    
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
    
            String filePath = "students.csv";
    
            try {
                BufferedReader reader = new BufferedReader(new FileReader(filePath));
    
                String line;
    
                while ((line = reader.readLine()) != null) {
                    String[] values = line.split(",");
    
                    for (String value : values) {
                        System.out.print(value + " ");
                    }
    
                    System.out.println();
                }
    
                reader.close();
    
            } catch (IOException error) {
                System.out.println("Error reading CSV file: " + error.getMessage());
            }
        }
    }
    

    This example is useful for beginner-level CSV understanding. In professional projects, a proper CSV parser is better because CSV data may contain commas inside quoted text.

    Java Example: Writing Simple CSV

    The following Java example writes student records into a CSV file.

    
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
    
            String filePath = "students.csv";
    
            try {
                FileWriter writer = new FileWriter(filePath);
    
                writer.write("rollNumber,name,marks\n");
                writer.write("101,Rahul,85\n");
                writer.write("102,Ayesha,92\n");
                writer.write("103,John,76\n");
    
                writer.close();
    
                System.out.println("CSV file written successfully.");
    
            } catch (IOException error) {
                System.out.println("Error writing CSV file: " + error.getMessage());
            }
        }
    }
    

    This creates a CSV file with one header row and three data rows.

    JavaScript Example: JSON Object

    JavaScript works naturally with JSON-like objects. The following example shows a student object.

    Prerequisites: To understand this example, you should know JavaScript objects, properties, arrays, console output, and basic JSON structure.
    
    const student = {
        rollNumber: 101,
        name: "Rahul",
        course: "Programming Fundamentals",
        marks: 85
    };
    
    console.log(student.name);
    console.log(student.marks);
    

    This object can be converted into JSON text when saving or sending data.

    JavaScript Example: Convert Object to JSON

    In JavaScript, JSON.stringify() is used to convert an object into JSON text.

    
    const student = {
        rollNumber: 101,
        name: "Rahul",
        course: "Programming Fundamentals",
        marks: 85
    };
    
    const jsonText = JSON.stringify(student, null, 4);
    
    console.log(jsonText);
    

    The output will be JSON text. The null, 4 part formats the JSON with indentation for better readability.

    JavaScript Example: Parse JSON Text

    In JavaScript, JSON.parse() is used to convert JSON text back into an object.

    
    const jsonText = `{
        "rollNumber": 101,
        "name": "Rahul",
        "course": "Programming Fundamentals",
        "marks": 85
    }`;
    
    const student = JSON.parse(jsonText);
    
    console.log(student.name);
    console.log(student.course);
    

    This is useful when data is read from a JSON file or received from an API.

    PHP Example: Working with JSON

    PHP can convert arrays into JSON and JSON text back into arrays or objects.

    Prerequisites: To understand this example, you should know PHP arrays, echo statement, variables, and basic JSON syntax.
    
    <?php
    
    $student = [
        "rollNumber" => 101,
        "name" => "Rahul",
        "course" => "Programming Fundamentals",
        "marks" => 85
    ];
    
    $jsonText = json_encode($student, JSON_PRETTY_PRINT);
    
    echo $jsonText;
    
    ?>
    

    In this example, json_encode() converts PHP array data into JSON text.

    C# Example: Simple CSV Writing

    The following C# example writes simple CSV content into a file.

    Prerequisites: To understand this example, you should know C# strings, arrays, file writing, exception handling, and basic CSV structure.
    
    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            string filePath = "students.csv";
    
            string[] lines = {
                "rollNumber,name,marks",
                "101,Rahul,85",
                "102,Ayesha,92",
                "103,John,76"
            };
    
            try
            {
                File.WriteAllLines(filePath, lines);
    
                Console.WriteLine("CSV file written successfully.");
            }
            catch (Exception error)
            {
                Console.WriteLine("Error writing CSV file: " + error.Message);
            }
        }
    }
    

    Common CSV Problems

    CSV looks simple, but there are some common problems that beginners should understand.

    Problem Explanation Example
    Comma inside value If a value itself contains a comma, simple splitting may fail. "Kolkata, West Bengal"
    Missing value Some rows may have empty fields. 101,Rahul,,85
    Extra value A row may contain more values than expected. 101,Rahul,Course,85,Extra
    Wrong column order Data may be interpreted incorrectly if column order changes. name,rollNumber,marks instead of rollNumber,name,marks
    Newline inside value Some values may contain line breaks. Address fields in quoted text
    Important Caution For professional CSV processing, use a proper CSV parser instead of manually splitting by comma in complex cases.

    Common JSON Problems

    JSON is powerful, but it has strict syntax rules. Small mistakes can make a JSON file invalid.

    Problem Wrong Example Correct Example
    Missing double quotes around key { name: "Rahul" } { "name": "Rahul" }
    Using single quotes { 'name': 'Rahul' } { "name": "Rahul" }
    Trailing comma { "name": "Rahul", } { "name": "Rahul" }
    Missing comma between fields { "name": "Rahul" "marks": 85 } { "name": "Rahul", "marks": 85 }
    Unmatched braces { "name": "Rahul" { "name": "Rahul" }
    Beginner Tip: JSON syntax is strict. Always check braces, commas, double quotes, and key-value formatting.

    Advantages of CSV

    CSV is simple and useful for many real-world tasks, especially when data is tabular.

    Benefits of CSV

    • Simple and easy to understand.
    • Good for rows and columns.
    • Can be opened in spreadsheet software.
    • Compact for flat data.
    • Easy to export reports.
    • Useful for student records, product lists, and attendance data.
    • Easy to read line by line.
    • Beginner-friendly for file handling practice.

    Limitations of CSV

    CSV is simple, but it is not suitable for every type of data.

    No Natural Nesting CSV is not good for nested objects such as student with address and course details.
    Comma Problems Values containing commas need special handling.
    Less Descriptive Data rows may be hard to understand without a header row.
    Weak Data Type Support CSV values are usually read as text and need conversion to numbers or booleans.

    Advantages of JSON

    JSON is widely used because it can represent structured data clearly.

    Benefits of JSON

    • Supports key-value pairs.
    • Supports nested objects.
    • Supports arrays.
    • Data is self-descriptive because keys explain values.
    • Widely used in APIs and web applications.
    • Good for configuration files.
    • Can represent complex objects naturally.
    • Supported by many programming languages.

    Limitations of JSON

    JSON is flexible, but it can be more verbose than CSV for simple table data.

    Larger for Flat Data JSON may take more space because keys are repeated for each object.
    Strict Syntax Small syntax mistakes can make JSON invalid.
    Not Ideal for Spreadsheet Editing CSV is usually easier to open and edit in spreadsheet software.
    Requires Parsing Programs must parse JSON before using it as objects or dictionaries.

    Best Practices for CSV and JSON

    Following best practices helps keep CSV and JSON files clean, readable, and reliable.

    Recommended Practices

    • Use CSV for simple table-like data.
    • Use JSON for structured or nested data.
    • Always include a header row in CSV files when possible.
    • Keep CSV column order consistent.
    • Use proper CSV parsing for complex CSV files.
    • Use valid JSON syntax with double quotes around keys.
    • Format JSON with indentation for readability.
    • Validate JSON before using it in a program.
    • Use UTF-8 encoding for both CSV and JSON files.
    • Keep file names meaningful, such as students.csv or student-profile.json.
    • Handle file reading and parsing errors properly.
    • Do not store sensitive data in plain CSV or JSON without protection.

    Common Mistakes Beginners Make

    Beginners often make mistakes while working with CSV and JSON because both formats have different rules.

    Common Mistakes

    • Using CSV for complex nested data.
    • Using JSON for very simple table data where CSV is enough.
    • Forgetting the CSV header row.
    • Changing CSV column order randomly.
    • Splitting CSV by comma without considering quoted commas.
    • Writing invalid JSON syntax.
    • Using single quotes in JSON.
    • Adding trailing commas in JSON.
    • Not handling file reading errors.
    • Not validating data before processing it.

    Better Approach

    • Choose CSV for flat rows and columns.
    • Choose JSON for objects and nested structures.
    • Use consistent CSV headers.
    • Use JSON validators when needed.
    • Use proper parsers for real projects.
    • Keep data formatting consistent.
    • Use meaningful keys in JSON.
    • Handle parsing errors safely.

    Debugging CSV and JSON Problems

    When CSV or JSON data does not work correctly, use a systematic debugging approach.

    Debugging Checklist

    • Check whether the file path is correct.
    • Check whether the file extension is correct.
    • For CSV, check whether rows have the correct number of columns.
    • For CSV, check whether commas inside values are handled properly.
    • For JSON, check whether all keys are in double quotes.
    • For JSON, check whether braces and brackets are balanced.
    • For JSON, check whether commas are placed correctly.
    • Check whether the file is saved using UTF-8 encoding.
    • Check whether the data is empty or missing required fields.
    • Use clear error messages while reading and parsing files.

    Mini Practice Activity

    Complete the following practice tasks to strengthen your understanding of CSV and JSON basics.

    Task Description Expected Learning
    Task 1 Create a students.csv file with roll number, name, and marks. Understand CSV row and column structure.
    Task 2 Read students.csv and display each student record. Practice CSV reading.
    Task 3 Create a student.json file containing one student profile. Understand JSON key-value structure.
    Task 4 Create a JSON file containing multiple student objects in an array. Practice JSON arrays.
    Task 5 Create a nested JSON object with student, course, address, and result. Understand nested JSON structure.
    Task 6 Compare whether CSV or JSON is better for student marks data. Practice choosing the correct format.

    Frequently Asked Questions

    1. What is CSV?

    CSV stands for Comma-Separated Values. It is a text-based file format used to store table-like data in rows and columns.

    2. What is JSON?

    JSON stands for JavaScript Object Notation. It is a text-based format used to store structured data using key-value pairs.

    3. Is CSV a text file?

    Yes. CSV is usually a text file because it stores data as readable characters.

    4. Is JSON a text file?

    Yes. JSON is also a text file because it stores structured data in readable text format.

    5. What is the main difference between CSV and JSON?

    CSV stores data in rows and columns, while JSON stores data using keys and values. CSV is better for simple tables, while JSON is better for structured and nested data.

    6. Which is easier for beginners, CSV or JSON?

    CSV is usually easier for simple table data. JSON may take slightly more practice, but it is very useful for modern programming and APIs.

    7. Can CSV store nested data?

    CSV does not naturally support nested data. JSON is better when data contains nested objects or arrays.

    8. Can JSON store multiple records?

    Yes. JSON can store multiple records using an array of objects.

    9. Where is CSV used in real life?

    CSV is used for spreadsheets, reports, student records, attendance records, product lists, and exported data.

    10. Where is JSON used in real life?

    JSON is used in APIs, web applications, configuration files, mobile apps, backend systems, and structured data exchange.

    Summary

    CSV and JSON are two very common text-based file formats used in programming. CSV is best for simple tabular data, while JSON is best for structured and nested data.

    CSV stores data in rows and columns. Each row usually represents one record, and values are separated by commas. It is useful for student marks, attendance records, product lists, reports, and spreadsheet data.

    JSON stores data using key-value pairs. It can represent objects, arrays, and nested structures. It is widely used in APIs, configuration files, application settings, and modern web development.

    A good programmer should know when to use CSV and when to use JSON. Choosing the correct format makes data easier to store, read, process, and maintain.

    Key Takeaway

    CSV is ideal for simple table-like data with rows and columns. JSON is ideal for structured data with key-value pairs, arrays, and nested objects. Both formats are important for file handling, data storage, APIs, reports, and real-world programming.