← All posts
6 min read

Data Formats: CSV, JSON, and XML for Exchanging Information

#technology#computer-science#data-formats#csv#json#xml
📑 On this page

Two systems can hold the same logical information yet fail to communicate if they disagree about how values are written.

A data format defines syntax and structure so software can serialize information into bytes and parse those bytes back into values.

CSV is suited to simple tables, while JSON and XML can represent labeled, nested structures.

No format is best for every job. Compatibility, shape, type fidelity, readability, size, validation, and tooling all matter.

A concrete example: one order

An order contains an ID, customer, and several items.

In a relational system, the order and items may occupy separate tables. For export or an API response, they can be represented in different formats.

CSV may use one row per item and repeat order-level values. JSON can nest item objects inside one order object. XML can represent the same hierarchy with elements and attributes.

The logical content is similar, but each format emphasizes a different structure.

CSV represents rows and fields

CSV means comma-separated values.

order_id,customer_id,sku,quantity
501,1042,A7,2
501,1042,B4,1

Its strengths include:

  • Simple tabular shape
  • Small overhead
  • Broad spreadsheet support
  • Easy streaming line by line
  • Familiar imports and exports

CSV works well when each record has the same flat fields.

CSV is less simple than it appears

What if a value contains a comma, quote, or newline?

id,description
1,"Large box, blue"
2,"Customer wrote:
""Leave at side door."""

Correct CSV parsers understand quoting rules. Splitting each line on commas does not.

CSV also lacks one universal convention for:

  • Character encoding
  • Date format
  • Null versus empty string
  • Decimal separator
  • Boolean values
  • Header presence
  • Line endings

The producer and consumer need a documented contract.

CSV has weak type information

Everything in a CSV file is written as text. A parser or import schema must decide whether 00123 is:

  • The number 123
  • A postal code that must retain leading zeros
  • A product identifier

Spreadsheet programs may automatically convert long identifiers, dates, and scientific-looking strings. This can corrupt data silently.

For controlled pipelines, define column types and validate imports rather than relying on guesses.

JSON represents values and nesting

JSON means JavaScript Object Notation, though it is language-independent.

{
  "orderId": 501,
  "customerId": 1042,
  "paid": true,
  "items": [
    { "sku": "A7", "quantity": 2 },
    { "sku": "B4", "quantity": 1 }
  ]
}

JSON supports:

  • Objects with named fields
  • Arrays
  • Strings
  • Numbers
  • Booleans
  • Null

Its direct mapping to common programming-language values makes it popular for web APIs and configuration.

JSON has limits too

Standard JSON does not include native values for:

  • Dates
  • Binary data
  • Arbitrary-precision decimals
  • Comments
  • References between objects

Dates are usually encoded as agreed strings. Binary values may be Base64-encoded, increasing size, or transmitted separately.

JSON numbers can also exceed the exact integer range of some language runtimes. Large identifiers are often safer as strings.

A syntactically valid JSON document can still violate the application's expected schema.

XML uses elements and attributes

XML means Extensible Markup Language.

<order id="501" customerId="1042" paid="true">
  <items>
    <item sku="A7" quantity="2" />
    <item sku="B4" quantity="1" />
  </items>
</order>

XML supports:

  • Nested elements
  • Attributes
  • Namespaces
  • Mixed text and markup
  • Comments
  • Rich schema languages
  • Document transformation tools

It remains common in enterprise integration, publishing, document standards, configuration, and protocols with established XML contracts.

XML is verbose but expressive

Opening and closing tags add size compared with compact JSON. That cost may be acceptable when:

  • Human-authored documents mix text and structure.
  • Namespaces combine several vocabularies.
  • Existing schema and transformation tooling matters.
  • Long-lived standards require explicit extensibility.

Compression often reduces repeated tag overhead during transmission.

The right comparison is not only raw character count. Consider the ecosystem and semantic requirements.

Schemas define stronger contracts

Formats define syntax. Schemas define which documents are valid for a particular use.

Examples include:

  • JSON Schema
  • XML Schema Definition
  • A CSV data dictionary
  • API specifications that describe request and response fields

A schema can state:

  • Required fields
  • Types
  • Allowed values
  • Numeric ranges
  • Nested structures
  • Compatibility rules

Validation should occur at trust boundaries, while applications still handle semantically invalid combinations that a basic schema cannot express.

Parsing safely matters

Never parse complex formats with ad hoc string operations.

Use maintained parsers and configure them securely.

Potential risks include:

  • CSV formulas executed by spreadsheet software
  • Extremely deep JSON causing resource exhaustion
  • Oversized payloads
  • Duplicate keys interpreted inconsistently
  • XML external entity behavior
  • Expansion attacks
  • Maliciously crafted input targeting parser bugs

Limit payload size, validate structure, disable unnecessary features, and treat imported content as untrusted.

Streaming versus loading everything

A small JSON response can be loaded into memory at once. A 100-gigabyte export cannot.

CSV naturally supports row-by-row streaming. XML supports streaming parsers that emit events as elements appear. Standard JSON documents can be streamed with specialized parsers, though newline-delimited JSON is often easier for record-oriented pipelines.

Format and file organization affect:

  • Memory usage
  • Partial processing
  • Error recovery
  • Parallelism
  • Ability to append records

Design for realistic data volume, not only sample files.

Versioning a format

Data contracts evolve.

Compatible changes may include adding optional fields that old consumers ignore. Breaking changes include renaming a required field, changing its type, or altering its meaning.

Robust consumers:

  • Ignore unknown fields when appropriate
  • Validate required fields
  • Avoid depending on field order
  • Handle missing optional values
  • Record contract versions when necessary

Producers should not reuse an existing field with a new meaning merely because its name is convenient.

Choosing among CSV, JSON, and XML

Choose CSV when:

  • Data is flat and tabular.
  • Spreadsheet compatibility matters.
  • Streaming rows is useful.

Choose JSON when:

  • Data contains objects and arrays.
  • Web and programming-language interoperability matters.
  • A concise labeled format is desirable.

Choose XML when:

  • Document markup, namespaces, or mature XML schemas matter.
  • An existing standard requires it.
  • Rich transformation and validation tooling is valuable.

Other formats such as Parquet, Avro, Protocol Buffers, and MessagePack may be better for analytics, compact binary transport, or strongly typed contracts.

Knowledge check

  1. Why is splitting a CSV line on commas unsafe?
  2. Why can leading zeros be lost during CSV import?
  3. Which value types does JSON directly support?
  4. Name one capability XML provides that is useful for document-oriented standards.
  5. Why does valid format syntax not prove valid application data?

The one idea to remember

A data format is an exchange contract. Choose CSV for simple tables, JSON for common nested application values, and XML for rich document and schema ecosystems, then validate and parse the chosen format deliberately.