JSON vs CSV vs YAML: Which Format Should You Use?
- JSON vs CSV vs YAML: Which Format Should You Use?
- The short version: the three rules
- What each format actually is
- JSON: the universal data exchange format
- CSV: the universal spreadsheet format
- YAML: the human-friendly configuration format
- Decision scenario 1: you are building a REST API
- Decision scenario 2: a business user needs the data in a spreadsheet
- Decision scenario 3: you are writing a configuration file
- Decision scenario 4: you are bulk-loading data into a database
- Decision scenario 5: a CI/CD pipeline or infrastructure-as-code tool
- Decision scenario 6: sharing data between two backend services you control
- Decision scenario 7: a data file that will be version-controlled in git
- The type coercion matrix: what survives conversion
- Practical checklist before converting
- Matching format to audience
- Tooling recommendations
- Closing thoughts
JSON vs CSV vs YAML: Which Format Should You Use?
Every developer reaches a point in a project where they have to make a decision that feels small but has lasting consequences: which data format should I use here? The three formats you will encounter most often are JSON, CSV, and YAML. Each one was designed with a specific job in mind, and choosing the wrong one creates unnecessary friction โ data that loses precision on import, config files that are painful to read, or APIs that return data your database cannot directly absorb.
This guide is a practical decision framework. For each realistic scenario you might encounter, it explains which format belongs there and why. Along the way it covers the structural characteristics that make each format suitable or unsuitable for a given job, so you can reason about new situations rather than just following a lookup table.
The short version: the three rules
Before going into depth, here is the quick decision guide:
- Choose JSON when you are exchanging data between two programs, especially over HTTP. Richly structured, widely supported, no ambiguity.
- Choose CSV when the data is tabular and the audience is a spreadsheet, database bulk loader, or data analyst. Smallest file size, universal support.
- Choose YAML when a human being is going to read and edit the file regularly, especially for configuration. Comments, multi-line strings, and clean indentation make it the best format for files that are maintained over time.
The rest of this article is the detail behind those rules.
What each format actually is
JSON: the universal data exchange format
JSON (JavaScript Object Notation) is a text-based format for representing structured data as a hierarchy of key-value maps (objects) and ordered lists (arrays). It supports six value types: string, number, boolean, null, object, and array. The object and array types can nest arbitrarily deeply, which is why JSON can represent almost any real-world data structure.
JSON was designed to be easy for machines to generate and parse. Its syntax is strict: keys must be quoted strings, trailing commas are not allowed, and there is no comment syntax. This strictness is a feature in API communication โ there is exactly one correct way to write any given value, which makes parsing unambiguous.
JSON is the standard wire format for REST APIs, GraphQL responses, browser-side storage (localStorage, IndexedDB), and a large fraction of modern configuration files (package.json, tsconfig.json, and others).
CSV: the universal spreadsheet format
CSV (Comma-Separated Values) is a tabular format: a first row of column headers followed by rows of values, each column separated by a comma. Its defining characteristic is simplicity โ so much simplicity that the format has no official type system, no standard for representing nulls, and no standard for handling commas inside values (though quoting with double quotes is the de facto convention).
That simplicity is also CSV's killer feature. Every spreadsheet application on the planet โ Excel, Google Sheets, LibreOffice Calc, Apple Numbers โ can open and export CSV files. Every relational database offers a CSV import path. Every data analysis tool, from R to pandas to Tableau, treats CSV as a first-class input. If the humans or tools on the receiving end of your data live in the spreadsheet world, CSV is the right choice.
The constraint you must always remember: CSV is flat. There is no nesting, no object hierarchy, no arrays inside rows. Each row is one record; each column is one field; every field is a string.
YAML: the human-friendly configuration format
YAML (YAML Ain't Markup Language) was designed specifically to be readable and writable by humans. Where JSON uses braces and brackets, YAML uses indentation. Where JSON forbids comments, YAML supports them with the # character. Where JSON requires quoting for strings, YAML often allows unquoted bare values.
YAML is a superset of JSON โ every valid JSON document is also valid YAML. But YAML's own syntax goes far beyond JSON: anchors (&name) and aliases (*name) let you define a value once and reference it in multiple places. Multi-line string literals (using | or >) let you embed long text without escape sequences. Explicit type tags let you annotate values with types the parser should use.
YAML dominates configuration-as-code: Kubernetes manifests, GitHub Actions workflows, GitLab CI pipelines, Docker Compose files, Ansible playbooks, and Helm charts are all YAML. The common thread is that these files are written and maintained by engineers over time, not generated by code.
Decision scenario 1: you are building a REST API
Use JSON.
REST APIs exist to exchange data between programs. JSON is the standard wire format for this job. Every HTTP client library in every language can parse JSON. Browser fetch and XMLHttpRequest handle JSON natively. GraphQL, which sits on top of HTTP, also returns JSON.
The one exception: if your API is primarily serving file downloads or bulk data exports that end users will open in spreadsheets, offering a CSV download endpoint (in addition to JSON) is good practice. But the API's default response format should be JSON.
Decision scenario 2: a business user needs the data in a spreadsheet
Use CSV.
If a stakeholder needs to open the data in Excel or Google Sheets, CSV is the cleanest path. JSON can be imported into spreadsheets but requires extra steps. CSV opens with a double-click.
The preparation work on your side: ensure the data is a flat array of records before converting. If your source is an API response with nested objects, extract the relevant fields and flatten them into simple key-value records first. A tool like the sourcecodestack JSON to CSV converter handles the mechanics of the conversion; the flattening is the conceptual step you need to do beforehand.
Also remember to handle character encoding. CSV exported from or imported to Excel on Windows defaults to Windows-1252 encoding. If your data contains any non-ASCII characters โ accented letters, Cyrillic, CJK characters โ ensure the file is explicitly saved and opened as UTF-8, or those characters will be corrupted.
Decision scenario 3: you are writing a configuration file
Use YAML (usually). Use JSON if tooling requires it.
YAML was built for config files. The reasons are practical:
- Comments. You can annotate every setting with a note explaining why it has that value. JSON has no comment syntax. Over the lifetime of a project, comments in config files save hours of archaeology.
- Readability. YAML's indented block style is easier to scan than JSON's nested braces, especially for files with many levels of nesting like Kubernetes deployments.
- Multi-line strings. YAML's literal block scalar (
|) lets you embed shell scripts, SQL queries, or long messages without backslash-escaping every newline. In JSON you would need\nthroughout.
The trade-off: YAML's flexibility comes at a cost. Indentation errors produce subtle bugs. YAML's implicit type coercion (bare yes parsed as boolean, bare 10 parsed as integer) occasionally surprises developers who intended a string. YAML 1.1 and YAML 1.2 have different rules about some of these implicit casts, and not all libraries implement the same version.
If the configuration file is machine-generated rather than human-maintained โ for example, a file that your build system writes and reads back โ JSON is actually the better choice. It is easier to generate correctly with standard library serialisers, and there is no risk of indentation errors.
Decision scenario 4: you are bulk-loading data into a database
Use CSV if the database supports it directly. Use JSON if you need to transform data in code first.
PostgreSQL's COPY command, MySQL's LOAD DATA INFILE, SQLite's .import, and SQL Server's BULK INSERT all accept CSV. For very large datasets (millions of rows), using the database's native CSV loader is orders of magnitude faster than inserting via an API loop.
The gotcha: CSV has no types, so the database applies the column types defined in the destination table's schema. Make sure the schema defines the correct types for numeric, boolean, and date columns, or they will be stored as text strings.
If you need to transform the data before loading โ merging fields from multiple CSV files, adding computed columns, normalising values โ it is often cleaner to convert CSV to JSON first, transform the JSON in code, and then insert via the API or an ORM. The type-coercion step that CSV-to-JSON conversion requires also gives you a natural place to validate and clean the data.
Decision scenario 5: a CI/CD pipeline or infrastructure-as-code tool
Use the format the tool requires (usually YAML).
Kubernetes, GitHub Actions, GitLab CI, CircleCI, Drone, Argo CD, Flux, and Helm all use YAML. Terraform uses its own HCL (HashiCorp Configuration Language) which is a superset of JSON. Pulumi uses general-purpose languages (TypeScript, Python, Go). AWS CloudFormation supports both JSON and YAML (YAML is recommended for human-authored templates).
For tools that accept both JSON and YAML (CloudFormation, some Kubernetes tooling), prefer YAML for files you author and maintain by hand, and prefer JSON for files you generate programmatically. This pattern โ YAML for humans, JSON for machines โ is a good general heuristic.
One practical tip: if you are troubleshooting a complex YAML manifest, converting it to JSON can help you see the structure clearly. Braces and brackets make nesting levels explicit in a way that indentation sometimes does not, especially when the file is hundreds of lines long. You can use a client-side converter so the manifest's credentials and internal addresses are never transmitted anywhere.
Decision scenario 6: sharing data between two backend services you control
Use JSON. Consider MessagePack or Protocol Buffers if performance is critical.
For internal service-to-service communication, JSON is the standard choice: easy to inspect in logs, easy to decode in any language, and well-supported by every framework. The overhead of JSON parsing is negligible for most workloads.
If you are moving very large volumes of data between services and parsing overhead is measurable โ for example, a high-frequency data pipeline processing millions of events per second โ binary formats like MessagePack (a binary JSON superset), Protocol Buffers, or Apache Avro are worth considering. They are faster to parse and produce smaller payloads. But they are harder to debug because you cannot read the raw bytes in a log. That is a trade-off that only matters at scale.
Decision scenario 7: a data file that will be version-controlled in git
Use JSON for data, YAML for config, and avoid CSV.
Git diffs are line-based. JSON and YAML both use one-line-per-field structures (when formatted consistently), which means changes show up clearly in diffs: you can see exactly which key changed from which value to which value.
CSV diffs are harder to read. A change to a field in the middle of a wide CSV row shows the entire row as modified. If the file is sorted differently between commits, git sees every row as changed, making the history almost unreadable.
For JSON files in git, always format them with consistent indentation (2 or 4 spaces) and sorted keys if possible. Unsorted keys cause spurious diffs when two processes write the same file in different orders.
The type coercion matrix: what survives conversion
When you convert between formats, data types are not always preserved. Here is what happens to each type in each direction:
JSON to CSV: Numbers, booleans, and nulls become strings. Nested objects and arrays cannot be represented and cause a conversion error unless you flatten them first.
CSV to JSON: All values arrive as strings. You must explicitly coerce numbers with Number() or parseInt(), booleans by comparing against "true" or "1", and nulls by checking for empty strings.
JSON to YAML: All JSON types are preserved. YAML has native representations for numbers, booleans, null, strings, objects (mappings), and arrays (sequences). Round-trip fidelity is high, but YAML comments and anchors are not representable in JSON, so they cannot be added through conversion.
YAML to JSON: Most YAML types survive. The exceptions: comments are discarded, anchors and aliases are resolved and inlined, and some YAML-specific features (like explicit type tags) may not have JSON equivalents.
CSV to YAML: Values arrive as strings (same as CSV to JSON). The result is a YAML sequence of mappings where every value is quoted as a string.
YAML to CSV: Only YAML documents that are a sequence of flat mappings can be converted to CSV. Nested mappings, sequences inside mappings, and other complex structures require flattening first.
Practical checklist before converting
Before you convert data between formats, run through this checklist:
- Is the source data valid? Validate your JSON, CSV, or YAML before trying to convert. A JSON syntax error or an extra comma produces a confusing error in the converter rather than a useful parse error in the source.
- Does the target format support the structure? If you are converting to CSV, verify the data is a flat array of records. If it is not, flatten it first.
- What types do you need to preserve? Plan your type-coercion step for CSV conversions. Write it down before you start; it is easy to forget.
- Will comments or metadata be lost? If you are converting YAML that has important comments (explaining why a config value is set), save the original YAML file before converting. The comments will not survive the round-trip.
- What is the character encoding? If the data comes from a source that might use non-UTF-8 encoding (such as CSV from Excel), convert to UTF-8 first.
- Are you handling the data securely? For sensitive data (API keys, PII, production credentials), use a tool that processes data locally in your browser rather than uploading it to a server.
Matching format to audience
The deepest principle underlying all these decisions is to match the format to the audience:
- Machines reading data at runtime: JSON
- Humans editing configuration by hand: YAML
- Business users or analysts opening data in a spreadsheet: CSV
- Databases performing bulk loads: CSV
- Version control and code review: JSON (for data), YAML (for config)
- Any situation involving sensitive data and an online tool: always verify the tool is client-side
When you are on the boundary โ for example, data that both a machine and a human will read โ lean toward JSON and add a comment in the code explaining the structure, rather than choosing YAML just for the comment syntax.
Tooling recommendations
For one-off conversions in the browser, the sourcecodestack JSON to CSV to YAML converter handles all six directions (JSON to CSV, JSON to YAML, CSV to JSON, CSV to YAML, YAML to JSON, YAML to CSV) and runs entirely client-side. Nothing is uploaded.
For scripted conversions in Node.js:
- YAML:
js-yaml(used by webpack, eslint, and most of the Node ecosystem) - CSV:
papaparsefor browser use;csv-parsefor Node streams - JSON:
JSON.parseandJSON.stringifyfrom the standard library
For scripted conversions in Python:
- YAML:
pyyamlorruamel.yaml(ruamel preserves comments on round-trips) - CSV:
csv.DictReader/csv.DictWriterfrom the standard library - JSON:
jsonfrom the standard library
For command-line workflows:
- jq โ a powerful JSON processor that can filter, transform, and reshape JSON from the command line
- yq โ a YAML processor that wraps jq's syntax for YAML files
- csvkit โ a suite of command-line tools for working with CSV (csvjson, csvpy, csvsql, and more)
Closing thoughts
JSON, CSV, and YAML are not competing formats โ they are complementary tools for different jobs. A mature project uses all three: JSON for its API, CSV for its data exports, and YAML for its deployment configuration. Understanding what each format can and cannot represent saves time debugging conversion errors, prevents silent data corruption, and helps you pick the right storage strategy from the start.
When you do need to convert between them, the key questions are: does the target format support the data's structure, what types will I lose, and is the conversion happening somewhere my data is safe? Answer those three questions first, and the conversion itself is straightforward.
You might also like
How to Compare Two Text Files Online (and Read the Differences)
How to Compare Two Text Files Online and Read the Differences At some point, almost every developer,โฆ
Read moreRegex Patterns Every Developer Should Know
Regex Patterns Every Developer Should Know Regular expressions are one of those tools that look intiโฆ
Read moreWhat Is JSON? Complete Guide to JSON Formatting
What Is JSON? Complete Guide to JSON Formatting JSON โ JavaScript Object Notation โ is the lingua frโฆ
Read more