JSON to CSV Converter

JSON to CSV Converter

JSON to CSV Converter

CSV Output:

To convert JSON to CSV (Comma-Separated Values), you need to transform the hierarchical JSON data structure into a flat table format typical of CSV files. Here’s a step-by-step guide on how to do this:

Understanding JSON and CSV

  • JSON (JavaScript Object Notation): A data format that stores data in key-value pairs and can include nested objects and arrays.
  • CSV (Comma-Separated Values): A tabular data format where each line represents a row, and columns are separated by commas.

Steps to Convert JSON to CSV

1. Flatten JSON Data

If your JSON data includes nested objects or arrays, you need to flatten it. This means converting nested structures into a single level. For example, an address object inside a person object needs to be flattened into a single row.

Example:

  • JSON:
    [
    {
    "name": "John",
    "age": 30,
    "address": {
    "street": "5th Avenue",
    "city": "New York"
    }
    },
    {
    "name": "Jane",
    "age": 25,
    "address": {
    "street": "Main Street",
    "city": "Los Angeles"
    }
    }
    ]
  • Flattened CSV:
    name,age,address.street,address.city
    John,30,5th Avenue,New York
    Jane,25,Main Street,Los Angeles

3. Using Excel or Google Sheets

  1. Google Sheets:
  2. Microsoft Excel:
    • Use Power Query to import JSON data.
    • Go to “Data” > “Get Data” > “From File” > “From JSON.”
    • Convert the imported data into a table and then save as CSV.

4. Using Programming Languages

You can write scripts to automate the conversion process.

  • Python:
    import pandas as pd
    import json

    # Load JSON data
    with open('data.json') as f:
    data = json.load(f)

    # Flatten JSON data
    df = pd.json_normalize(data)

    # Convert to CSV
    df.to_csv('data.csv', index=False)

  • JavaScript (Node.js):
    const fs = require('fs');
    const json2csv = require('json2csv').parse;

    // Load JSON data
    const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));

    // Convert to CSV
    const csv = json2csv(data);

    // Save CSV file
    fs.writeFileSync('data.csv', csv);

5. Using Command-Line Tools

  • jq (Command-line JSON processor):
    jq -r '[.[] | {name, age, address: .address.street + ", " + .address.city}] | (first | keys_unsorted) as $keys | map([.[ $keys[] ]]) | @csv' data.json > data.csv

Summary

Converting JSON to CSV involves flattening the JSON structure and then using tools or scripts to perform the conversion. You can use online converters, spreadsheet software, or programming languages like Python and JavaScript to achieve this. Each method has its own advantages depending on the complexity of your JSON data and the tools you have at hand.