惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

aimingoo的专栏
aimingoo的专栏
宝玉的分享
宝玉的分享
博客园 - 【当耐特】
博客园 - 司徒正美
L
LangChain Blog
有赞技术团队
有赞技术团队
大猫的无限游戏
大猫的无限游戏
Stack Overflow Blog
Stack Overflow Blog
Engineering at Meta
Engineering at Meta
U
Unit 42
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
博客园 - 叶小钗
H
Hackread – Cybersecurity News, Data Breaches, AI and More
J
Java Code Geeks
月光博客
月光博客
量子位
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园_首页
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
Google DeepMind News
Google DeepMind News
云风的 BLOG
云风的 BLOG
D
DataBreaches.Net

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Converting JSON to CSV: How to Flatten Nested Data for Sp...
Snappy Tools · 2026-05-14 · via DEV Community

JSON and CSV both represent tabular data, but they handle structure very differently. JSON can nest objects and arrays indefinitely. CSV is flat — two dimensions, rows and columns. That gap is where most conversion bugs live.

Here is a practical guide to converting JSON to CSV without losing data or your mind.

Why JSON to CSV Conversion Is Harder Than It Looks

A flat JSON array is easy. This converts in seconds:

[
  { "id": 1, "name": "Alice", "role": "admin" },
  { "id": 2, "name": "Bob",   "role": "editor" }
]

Enter fullscreen mode Exit fullscreen mode

id,name,role
1,Alice,admin
2,Bob,editor

Enter fullscreen mode Exit fullscreen mode

The problem starts when your real-world JSON looks like this:

[
  {
    "id": 1,
    "name": "Alice",
    "address": {
      "city": "London",
      "zip": "EC1A"
    },
    "tags": ["admin", "billing"]
  }
]

Enter fullscreen mode Exit fullscreen mode

Now you have choices to make. Should address.city become a column? Should tags become a comma-separated string, or multiple columns, or separate rows?

The answer depends on what you are doing with the CSV.

Approach 1: Dot-Notation Flattening

The most common approach for nested objects is to flatten them with dot notation:

id,name,address.city,address.zip,tags
1,Alice,London,EC1A,"admin,billing"

Enter fullscreen mode Exit fullscreen mode

Here is a minimal JavaScript function that does this:

function flattenObject(obj, prefix = '') {
  return Object.entries(obj).reduce((acc, [key, val]) => {
    const fullKey = prefix ? `${prefix}.${key}` : key;
    if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
      Object.assign(acc, flattenObject(val, fullKey));
    } else {
      acc[fullKey] = Array.isArray(val) ? val.join(';') : val;
    }
    return acc;
  }, {});
}

Enter fullscreen mode Exit fullscreen mode

Then convert the array:

function jsonToCSV(data) {
  const flattened = data.map(row => flattenObject(row));
  const headers = [...new Set(flattened.flatMap(Object.keys))];

  const rows = flattened.map(row =>
    headers.map(h => {
      const val = row[h] ?? '';
      // Escape values that contain commas, quotes, or newlines
      const str = String(val);
      if (str.includes(',') || str.includes('"') || str.includes('\n')) {
        return `"${str.replace(/"/g, '""')}"`;
      }
      return str;
    }).join(',')
  );

  return [headers.join(','), ...rows].join('\n');
}

Enter fullscreen mode Exit fullscreen mode

The key part people forget: proper CSV escaping. A value like "Hello, world" contains a comma. Without quotes, it splits into two columns. Without doubling internal quotes, it breaks the parser.

Approach 2: Stringify Mode

Sometimes you do not need to flatten nested data. You just need it in a spreadsheet for a quick review. In that case, stringify the complex values:

function flattenShallow(obj) {
  return Object.fromEntries(
    Object.entries(obj).map(([k, v]) => [
      k,
      typeof v === 'object' && v !== null ? JSON.stringify(v) : v
    ])
  );
}

Enter fullscreen mode Exit fullscreen mode

This keeps columns clean but stores {"city":"London","zip":"EC1A"} as a raw string in the cell. Readable, but you cannot sort or filter by nested properties.

Approach 3: Explode Arrays to Multiple Rows

If you have a one-to-many relationship — one user with multiple orders — you might want each array element as a separate row:

{ "userId": 1, "orders": [{"id": "A1"}, {"id": "A2"}] }

Enter fullscreen mode Exit fullscreen mode

Becomes:

userId,orders.id
1,A1
1,A2

Enter fullscreen mode Exit fullscreen mode

This produces more rows but is often the right shape for database imports.

Handling Edge Cases

Different objects with different keys. Real APIs return inconsistent shapes. Row 1 might have firstName, row 2 might have first_name. Your header extraction needs to union all keys, not just read the first row:

const headers = [...new Set(data.flatMap(Object.keys))];

Enter fullscreen mode Exit fullscreen mode

Null and undefined values. Use ?? '' (nullish coalescing) rather than || '' — a value of 0 or false is falsy but valid and should not be replaced with an empty string.

Unicode and special characters. Emoji, accented characters, and right-to-left text all survive in CSV as long as you save the file as UTF-8. If your downstream tool opens it in Excel, Excel may interpret the encoding wrong. Adding a BOM () at the start of the file fixes this for most Excel users.

Number formats. A zip code like 00123 is a string, not the number 123. If you stringify everything, it survives. If you try to type-detect values, be careful — leading zeros mean the field is a string.

Triggering a File Download

Once you have the CSV string, downloading it from the browser is three lines:

function downloadCSV(csvString, filename = 'export.csv') {
  const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

Enter fullscreen mode Exit fullscreen mode

No libraries needed. Works in every modern browser.

When to Use a Library

For production use with complex data, consider Papa Parse — it handles all edge cases and is the standard CSV library for JavaScript.

For quick one-off conversions — pasting an API response and getting a CSV for a spreadsheet — you do not need a library at all.

The SnappyTools JSON to CSV Converter handles nested objects with dot-notation flattening, stringify mode for complex values, live CSV preview, and file download. It runs entirely in your browser with nothing uploaded.

Summary

  • Flat JSON arrays: trivial to convert
  • Nested objects: flatten with dot notation or stringify
  • Arrays of values: join with separator or explode to rows
  • Always escape commas, quotes, and newlines in cell values
  • Union all keys across all rows, not just the first row
  • For browser downloads, use Blob + URL.createObjectURL — no dependencies needed