Data Conversion Tools for Professional Workflows (2026)
Most conversion tutorials stop at "use a converter." This one covers the mechanics and the judgment: which conversions are lossless and which lose information, how to write a mapping spec that survives review, how to batch convert with jq, yq, and pandoc, how encoding bugs masquerade as format bugs, why JSON to XML usually grows by 30 to 50 percent, and how to prove a conversion is information-preserving with a round-trip test.
The Data Conversion Landscape
Data conversion is the everyday work of moving structured information from one format to another so a different system can read it. The five conversions that show up constantly in professional workflows are CSV to JSON, JSON to YAML, JSON to XML, Excel to CSV, and XML to JSON. Each pair has its own mechanics, its own failure modes, and its own reason for being the right choice in a specific context. Treat them as a small toolbox, not a single hammer.
The landscape divides cleanly along two axes: text versus binary, and tabular versus hierarchical. CSV and Excel are tabular. JSON, YAML, and XML are hierarchical (XML technically a tree, but the same shape in practice). Conversions inside the same axis are easier: JSON to YAML is a re-serialization of the same tree, and CSV to Excel is a re-serialization of the same grid. Cross-axis conversions, such as CSV to JSON or XML to JSON, force a structural decision about how flat rows become nested objects or how attributes become keys.
| Conversion | Axis change | Fidelity | Typical driver |
|---|---|---|---|
| CSV ↔ JSON | tabular → hierarchical | lossy for nested data | APIs that consume JSON from spreadsheets |
| JSON ↔ YAML | same axis | lossless | human-readable config files |
| JSON ↔ XML | same axis, different model | lossy without a mapping spec | SOAP or legacy enterprise systems |
| Excel ↔ CSV | same axis, richer to poorer | lossy for formulas and sheets | data exchange between spreadsheet and text tools |
| XML ↔ JSON | same axis, different model | lossy without a mapping spec | API modernization away from XML payloads |
The developer tools guide catalogs where conversion sits in the broader toolchain; this article stays on the mechanics. When you convert anything that came from a web page, the HTML to markdown conversion guide is the sibling that covers the document side of the same workflow, and the markdown to HTML tool reverses it for publishing.
The Semantic Fidelity Problem: Lossless vs Lossy
Two conversions are mathematically lossless: JSON to YAML and YAML to JSON. Both formats model the same three primitive types (scalars, sequences, mappings), so converting back and forth preserves every value, every type, and every nesting level. You can convert a JSON file to YAML, edit it by hand, and convert it back to JSON without losing anything structural.
XML to JSON is not lossless, even though both formats look hierarchical. XML has features JSON does not have a native slot for: attributes on elements, CDATA sections, comments, namespace prefixes, mixed content (text and child elements interleaved inside one element), and ordered sibling elements with the same name. JSON has features XML does not have a native slot for: arrays of distinct heterogeneous values, and a clean distinction between a number, a string, and a boolean. A round-trip JSON → XML → JSON that uses a generic converter will usually preserve data but may not preserve structure: arrays of one element collapse to a single object, attribute names acquire @ prefixes, and CDATA wrappers become plain strings.
CSV to JSON is lossy in the other direction. CSV has no native way to express nested objects, arrays, or typed values. A CSV cell that reads 42 might be a number or a string; a CSV row has no notion of a sub-record. A JSON file with nested objects must be flattened to fit CSV, and the flattening is a one-way operation unless the structure was trivial to begin with.
Excel to CSV is the most quietly lossy of the common conversions. An Excel workbook can hold multiple sheets, formulas, formatting, named ranges, and charts. CSV can hold none of those. When you export a multi-sheet workbook to CSV, the export usually saves only the active sheet, and every formula becomes its last calculated value. That is correct for data delivery but wrong for archival.
For worked XML conversions the JSON formatter shows the resulting tree, and the JSON validator confirms it parses; together they form the smallest useful verification pair for any XML to JSON pipeline. When the source carries binary payloads, the base64 encoder/decoder is the safe transport layer that keeps those bytes intact through any text-format conversion.
The Schema-Preserving Conversion Pattern
When a conversion is structurally lossy, the professional move is to write down the mapping decisions in a mapping specification before you touch any data. A mapping spec is a small document, usually YAML or JSON, that declares for every source field: the target key name, the target type, the default value if missing, and the rule for nulls. It is the contract your converter code is allowed to follow, and it is what your reviewers check when they want to know why customer_id became customerId.
The pattern is the same whether the source is XML, CSV, or a database export. Three pieces of information must be explicit: how attributes are represented (commonly @attr or _attr), how text and CDATA are represented (commonly #text or _), and how repeated elements are represented (always an array, even when one element is present, so the consumer does not have to special-case singletons). Libraries like fast-xml-parser and xml2js implement exactly these conventions; the spec is what you hand to a teammate who has not seen the code yet.
# mapping-spec.yaml: contract for an XML → JSON conversion
source_format: xml
target_format: json
conventions:
attributes: "@attr" # <record id="42"> -> {"@attr":{"id":"42"}}
text: "#text" # <name>Alice</name> -> {"name":{"#text":"Alice"}}
repeated: "always_array" # <item>one</item> -> [{"#text":"one"}]
fields:
- source: "//record/@id"
target: "id"
type: "string" # keep as string; do not infer integer
- source: "//record/name"
target: "name"
type: "string"
nullable: true
With a spec in place, the converter is boring: read the spec, walk the source tree, emit the target. Boring is the goal. The mapping decisions live in one reviewable file, the code does not have to encode them, and a teammate can audit the spec without reading the implementation. Storing the spec next to the data, and the data next to its documentation, is the discipline covered in our documentation best practices guide.
Batch Conversion Workflows with jq, yq, and pandoc
For one file at a time, a browser-based tool is enough. For a hundred or a thousand files, the command line is the right tool. Three utilities cover most professional needs: jq for JSON to JSON reshaping, yq for YAML to JSON and back, and pandoc for document formats. All three are scriptable, all three read from stdin and write to stdout, and all three compose cleanly with shell pipelines.
jq: reshape JSON in a pipeline
Convert a flat CSV export to a keyed JSON object so lookups are O(1). The -R flag reads raw lines, -s slurps them into an array, and a filter reshapes the array into an object keyed by id.
# Convert users.csv (id,name,email) to a JSON object keyed by id
jq -Rn '
[ inputs | split(",") | {id:.[0], name:.[1], email:.[2]} ]
| map({key: .id, value: .})
| from_entries
' users.csv > users.json
yq: YAML and JSON, both directions
Convert every YAML config in a directory to JSON in one pass. The -p flag sets the input format and -o sets the output format. Pair with a shell glob to batch.
# Convert all YAML files in this directory to JSON, in place by extension
for f in config/*.yml; do
yq -p yaml -o json "$f" > "${f%.yml}.json"
done
# And back the other way
yq -p json -o yaml users.json > users.yml
pandoc: document format translation
Convert markdown documentation to HTML for publishing, or HTML to markdown for editing. Pandoc handles the dialect quirks that break naive converters, including tables, fenced code blocks, and footnotes.
# Markdown to standalone HTML
pandoc README.md -f gfm -t html5 -s -o README.html
# HTML to GitHub-flavored markdown
pandoc docs.html -f html -t gfm -o docs.md
Batch scripts must log every output, because a script that exits zero can still emit empty files when an input is malformed. Tee the converter's stdout and stderr into a per-file log, and validate every output before declaring the batch done. The developer workflow for testing the regex that powers many of these batch extractors is the regex tester developer guide, and the underlying mechanics are in the regex testing guide. For the toughest parsing cases, the regex tester ultimate guide covers lookarounds and backreferences.
Data Validation Before and After Conversion
A conversion without validation is a guess. The professional workflow validates the input before converting, so the converter never sees malformed data, and validates the output after converting, so downstream systems never see broken data. Two layers of validation catch different problems: schema validation confirms structure, and content validation confirms semantics.
Schema validation
JSON Schema describes the shape of a JSON document: required keys, allowed types, value ranges, and array lengths. XML Schema (XSD) does the equivalent for XML. CSV has no formal schema language, but a CSV dialect declaration (delimiter, quote char, escape char, header presence) catches most parsing problems before they corrupt downstream columns.
# Validate a JSON file against a schema using python jsonschema
python3 -c "
import json, jsonschema
schema = json.load(open('user.schema.json'))
data = json.load(open('users.json'))
jsonschema.validate(instance=data, schema=schema)
print('valid')
"
Content validation
Schema says a field is a string. Content validation says the string is a real email, a real UUID, or a real date. This is where conversion pipelines leak: a CSV import writes the literal "null" string into a field that should be JSON null, and the downstream system crashes hours later. A one-line check at the boundary catches it now. When the field is an identifier that has to survive every conversion intact, a UUID (covered in our UUID generator developer guide) is the right choice: it has no encoding ambiguity and no semantic drift.
The two layers compose. Schema validation runs first because it is cheap and catches structural problems fast; content validation runs second because it is field-specific and slower. A round-trip test, covered below, is the strongest form of content validation because it checks the conversion itself, not just the format of the output. For ad-hoc checking, the JSON validator confirms an output file parses, and the JSON formatter shows whether the structure matches what you expected at a glance.
Character Encoding Pitfalls: UTF-8 BOM, UTF-16, ASCII
Most conversion bugs that look like format bugs are actually encoding bugs. The bytes are correct; the reader is reading them as the wrong character set. Three encodings cause almost all of the trouble: UTF-8 with a byte order mark, UTF-16, and legacy ASCII.
UTF-8 BOM: three bytes that break JSON parsers
The UTF-8 byte order mark is three bytes: EF BB BF. It is invisible in most text editors, but a JSON parser reading the file expects the first byte to be { or [, sees EF, and refuses. RFC 8259 explicitly says JSON files should not begin with a BOM. The fix is to write UTF-8 without a BOM. If a file already has one, decode with utf-8-sig in Python, which strips the mark, or run the file through a one-liner.
# Strip a UTF-8 BOM from a file (Python)
python3 -c "import sys; sys.stdout.buffer.write(open(sys.argv[1],'rb').read().lstrip(b''))" in.json > out.json
# A BOM-prefixed JSON file is 10 bytes; the same file without is 7 bytes
# Many parsers reject the 10-byte form outright
UTF-16: doubles the byte count of ASCII content
UTF-16 uses two bytes per character for ASCII content. An ASCII JSON document 52 bytes long becomes 104 bytes in UTF-16. UTF-16 also requires a BOM (two bytes: FF FE for little-endian, FE FF for big-endian) to disambiguate endianness. Use UTF-16 only when a downstream tool requires it; modern JSON and XML parsers all accept UTF-8.
| String | UTF-8 bytes | UTF-16 bytes | Ratio |
|---|---|---|---|
A | 1 | 2 | 2× |
hello | 5 | 10 | 2× |
€ (euro sign) | 3 | 2 | 0.67× |
中 (a CJK character) | 3 | 2 | 0.67× |
| 52-byte ASCII JSON | 52 | 104 | 2× |
ASCII: the silent truncation
Legacy systems that declare ASCII cannot represent any character above code point 127, which includes the euro sign, all accented Latin characters, and every CJK character. A conversion from UTF-8 to ASCII silently replaces those characters with ? or drops them. Always confirm the target encoding can represent every character in the source before you write. When the source is text data headed for a URL or HTTP header, the URL encoder/decoder handles percent-encoding safely, and the base64 encoder/decoder makes binary data safe for text transport without any encoding ambiguity.
Size Growth: Why JSON to XML Usually Gets Bigger
XML repeats every tag name twice, once to open and once to close. JSON repeats every key name once. The consequence is that JSON to XML conversion grows the file by roughly 30 to 50 percent for typical records, and the growth is not uniform: it depends on the ratio of key length to value length.
The headline comparison
A single-user record written as XML and as JSON, both files terminated by a newline (the way they would actually live on disk):
<user>John</user> (18 bytes, with newline)
{"user":"John"} (16 bytes, with newline)
For that record, XML is 2 bytes larger, a 12.5 percent overhead. The XML closing tag </user> costs 7 bytes; the JSON punctuation ", ", :, ", ", {, } costs 7 bytes too, but JSON saves the closing tag. That is the whole story.
When JSON is actually bigger
For very short values, the closing-tag cost is small enough that JSON's brace and quote overhead exceeds it. A single tiny field: <a>x</a> is 8 bytes, while {"a":"x"} is 9 bytes. JSON loses by one byte. Add the newline a file actually has and JSON is 10 bytes; XML with the newline is 9. For tiny records, JSON can be larger.
Worked example, realistic record
A user record with id, name, email, and active flag, written as JSON and as XML with element-style children:
{"user":{"id":42,"name":"John Doe","email":"john@example.com","active":true}} (77 bytes)
<user><id>42</id><name>John Doe</name><email>john@example.com</email><active>true</active></user> (110 bytes)
That is a 42.9 percent increase, squarely in the 30 to 50 percent range cited for typical records. The XML file is 33 bytes larger, and almost all of those 33 bytes are closing tags.
Mitigations that work
- gzip on the wire. Repeated tag names compress extremely well; gzip typically erases most of the XML overhead on transport. The on-disk and in-memory cost remains.
- Attributes instead of child elements. An XML attribute has no closing tag, so id-as-attribute is shorter than id-as-element. A record of
<record id="42">is 73 bytes against 76 bytes for the element form, still longer than the 52-byte JSON, but the gap narrows. - JSON for new APIs. When the choice is yours and you do not have a legacy XML consumer, ship JSON. The wire cost is lower, the parser cost is lower, and the schema ecosystem is more familiar to current developers.
The size story is one place where data conversion overlaps with code minification: both trades are about reducing the bytes the wire carries without changing what the receiver parses. The code minification best practices guide covers the equivalent discipline for CSS and JavaScript. And when those bytes flow through static publishing, the static site generators guide shows how the same byte discipline applies at build time.
The Round-Trip Test: Convert A → B → A and Compare
The strongest test of a conversion is to run it backwards and compare. If you convert JSON to XML and back to JSON, the final JSON should be semantically identical to the original. The comparison must be semantic, not byte-wise: parse both JSON files and compare the object trees, parse both XML files and compare the element and attribute trees. Whitespace, key order, and indentation are not semantic and should be ignored.
A round-trip script in Python
import json, subprocess, sys
# Step 1: original JSON
src = {"user": {"id": 42, "name": "John", "active": True}}
src_text = json.dumps(src, separators=(',', ':'))
# Step 2: JSON -> XML via a converter (pseudocode)
xml_text = json_to_xml(src_text)
# Step 3: XML -> JSON via the same converter backwards
roundtrip_text = xml_to_json(xml_text)
roundtrip = json.loads(roundtrip_text)
# Step 4: semantic comparison, not byte comparison
if roundtrip == src:
print("round-trip OK")
else:
print("round-trip DRIFT:", diff(src, roundtrip))
sys.exit(1)
A round-trip test that fails tells you exactly which feature the converter does not preserve. A common pattern: arrays of one element collapse to a single object after XML round-trip, because XML has no structural distinction between "one element" and "a list with one element." The fix is in the mapping spec (always emit an array), and the round-trip test is what tells you the spec was needed.
What a passing round-trip proves
A passing round-trip proves the conversion is information-preserving for the cases you tested. It does not prove the conversion is information-preserving for cases you did not test. Run round-trip on representative inputs: a small record, a large nested record, a record with arrays of one, a record with empty strings, a record with null values, a record with unicode characters. A round-trip that passes on a small record can fail on a record with a single-element array. Always run a varied corpus, not just one happy-path example.
The Conversion Workflow: Pick, Transform, Validate, Round-Trip, Ship
Tools do not replace the mechanics above; they automate them. The workflow that consistently produces trustworthy conversions takes five steps, and each step has a free tool that does the work.
Step 1: Pick the source and the target
Decide what you have (CSV from a spreadsheet, JSON from an API, XML from a legacy system) and what you need (JSON for a modern API, YAML for human editing, CSV for a spreadsheet). The choice of target is governed by the downstream system, not by personal preference. The developer tools guide maps which formats which tools consume.
Step 2: Transform with a tool, not a script
For one file, use a browser-based tool. For a batch, use jq, yq, or pandoc. Avoid hand-written conversion scripts that walk the source and emit the target; they almost always miss an edge case (single-element arrays, null versus empty string, attribute versus text) that a mature tool has already handled. The JSON formatter, JSON validator, HTML to markdown tool, and markdown to HTML tool cover the one-file cases.
Step 3: Validate the output
Run schema validation on the output before you ship it. For JSON, a JSON Schema. For XML, an XSD. For CSV, a dialect declaration. A file that parses is not the same as a file that conforms; only schema validation distinguishes them. The JSON validator catches the first kind of error.
Step 4: Round-trip the conversion
Convert the output back to the source format and compare semantically. A passing round-trip is the strongest evidence that the conversion is information-preserving for the record you tested. Run it on a varied corpus, not just one happy path.
Step 5: Ship and document
Commit the mapping spec next to the converted data, write a one-paragraph note about which conversions were lossless and which were lossy, and link to the original source so a future reader can re-derive the target. The documentation discipline is the documentation best practices guide; for the broader habit of writing about your tools, the markdown best practices guide and the GitHub markdown guide cover the source-side habits, and the markdown platforms guide covers which platform consumes which dialect.
7 Common Conversion Mistakes (and the Fix for Each)
- Trusting a generic XML to JSON converter. Generic converters drop attributes, collapse single-element arrays, and lose CDATA semantics. Fix: write a mapping spec, pick a converter that implements the spec's conventions, and round-trip before you ship.
- Shipping a UTF-8 file with a BOM. Three invisible bytes break JSON parsers and confuse downstream tools. Fix: write UTF-8 without a BOM; strip the mark with
utf-8-sigif it has already been written. - Inferring types from CSV cells. A CSV cell that reads
42is a string until you decide otherwise. Fix: declare the type in the mapping spec, do not let the converter guess, and never let"null"the string silently become JSONnull. - Comparing byte-for-byte after a round-trip. Whitespace and key order differ between converters; byte comparison always fails. Fix: parse both sides and compare the object trees, ignoring whitespace and key order.
- Forgetting Excel sheets and formulas. An Excel to CSV export drops every sheet except the active one and replaces formulas with values. Fix: export each sheet explicitly, archive the workbook, and document that formulas have been flattened.
- Hardcoding the encoding in the converter. A converter that assumes UTF-8 will misread a UTF-16 file as garbage. Fix: declare the encoding explicitly in the XML declaration, read with the right codec in code, and fail loudly on encoding mismatches.
- Treating JSON to YAML as free. JSON to YAML is lossless, but YAML has pitfalls of its own: tabs are not allowed for indentation, some strings need quoting, and the same value can render in multiple valid ways. Fix: convert with a mature tool like yq, not by hand, and validate the output with a YAML parser.
Every one of these is a workflow problem as much as a code problem, which is why the workflow above ends with validation and round-trip rather than with the conversion itself.
Frequently Asked Questions
Related Articles
Regex Testing Guide
The cluster pillar for testing pattern behavior before you split, parse, or extract from converted data.
Regex Tester Guide
Anchors, quantifiers, and capture groups for reliable field extraction from CSV and JSON inputs.
Regex Tester Ultimate Guide
Lookarounds, backreferences, and atomic groups for handling messy real-world records.
Regex Tester Developer Guide
The developer workflow for shipping regex-based transformers and parsers with confidence.
Markdown Best Practices
Clean source markdown survives every downstream HTML, JSON, and YAML conversion.
Markdown Platforms
Which platforms accept which markdown dialects, so conversions target the right flavor.
GitHub Markdown Guide
GitHub-flavored markdown quirks that survive HTML conversion and break in plain markdown.
HTML to Markdown Conversion
The reverse pipeline: turn HTML documentation back into editable markdown.
Code Minification Best Practices
Minification is itself a lossy text-format conversion governed by the same rules.
Static Site Generators
Static generators consume YAML, JSON, and TOML front matter to produce HTML at build time.
Developer Tools Guide
The broader developer tool landscape that data conversion sits inside.
UUID Generator Developer Guide
UUIDs as lossless cross-format identifiers that survive any conversion intact.
Conclusion: Conversions You Can Defend
Professional data conversion is not a format swap; it is a decision about what information to keep, what to flatten, and what to document. JSON to YAML is free, XML to JSON is not, and the difference is whether the source and target share a data model. The discipline that survives review is the same across every pair: pick the right target, transform with a mature tool, validate against a schema, round-trip against the source, and ship the mapping spec alongside the data.
When you are ready to run a conversion, open the JSON formatter to shape the output, the JSON validator to confirm it parses, the HTML to markdown tool for the document side, and the markdown to HTML tool to publish the result. More guides on developer workflows are catalogued on the NoCostTools blog.