Convert GraphQL results to CSV
What converting GraphQL results to CSV changes, what flattening can drop, and how to keep the file readable and usable in spreadsheets and other tools.
A GraphQL API returns JSON shaped like the query that requested it: objects inside objects, lists inside lists. CSV is a flat grid of rows and columns. Turning one into the other always requires decisions about how to flatten that structure, and some of those decisions discard information. This review explains what the conversion changes, what it can silently lose, and how to tell whether the resulting file will still be readable and usable where you plan to send it.
Is the conversion suitable for your use?
Converting GraphQL output to CSV is worth doing when the destination expects a flat table, such as a spreadsheet, a bulk-import form or a reporting tool, and when the data is mostly one record per row. The main benefit is that anyone can sort, filter and chart the result without writing code. The decisive tradeoff is structure: nested objects, lists and type information either get spread across extra columns, packed into single cells or dropped. If the meaning of your data depends on that structure, keep the JSON.
- Good fit: a list of records with mostly scalar fields, such as users, orders or issues, headed for a spreadsheet or import tool.
- Good fit: a one-off export where a person needs to scan, sort or filter values.
- Poor fit: deeply nested results where a child list can have many items per parent, such as orders with line items with discounts.
- Poor fit: results that will be fed back into another program, where JSON keeps types and structure intact.
- Plain text is better: a single record or a handful of values being shared in a message or document, where a sentence or short list reads more easily than comma-separated fields.
What the conversion actually changes
A GraphQL response is a JSON object with a data entry holding the requested fields, an errors entry when something went wrong, and sometimes an extensions entry. Inside data, each key is a field name or the alias given in the query, and the GraphQL specification expects fields to appear in the same order as they were selected. CSV, as described in RFC 4180, is a sequence of lines, each containing fields separated by commas, with an optional header line. A field that contains a comma, a double quote or a line break is wrapped in double quotes, and any double quote inside it is written twice. TSV uses tabs instead of commas and, under its common registration, has no quoting mechanism at all, so tabs and line breaks inside values must be removed or escaped by convention.
The conversion is therefore a change to stored characters, not a change in presentation. Values are rewritten as delimited text, structure is replaced by column names and row repetition, and type information is lost: in the CSV file, the string 42, the integer 42 and a missing value written as an empty cell are no longer distinguishable by type. Each kind of nesting needs its own flattening decision.
| Nested shape | Common approach | Tradeoff |
| Nested object (address.city) | One column per leaf field, named with dot notation | Readable, but column count grows with depth and every possible field needs a column |
| List of scalars (roles) | Join values into one cell with a separator such as a semicolon | Compact, but breaks if a value contains the separator and is harder to filter |
| List of objects (line items) | One row per list item, repeating parent fields | Easy to filter, but duplicates parent data and inflates totals if summed naively |
| Any nested value | Write the nested part as a JSON string inside the cell | Nothing is lost, but the cell is hard to read and needs parsing later |
| Connection wrapper (edges and node) | Drop the wrapper and use each node as a row | Usually what readers want, but cursors and page info disappear |
| Union or interface results | Include __typename as a column; leave inapplicable fields empty | Preserves which type each row is, at the cost of sparse columns |
The following illustrative response uses a common connection pattern. It is a constructed example, not output from any particular API.
{
"data": {
"users": {
"edges": [
{ "node": { "id": "0012", "name": "Ana, Ruiz", "roles": ["admin", "editor"], "address": { "city": "Austin" } } },
{ "node": { "id": "0047", "name": "Lee \"Sam\" Park", "roles": [], "address": null } }
]
}
}
}
Flattened with dot-notation headers and roles joined by semicolons, it becomes:
id,name,roles,address.city
0012,"Ana, Ruiz",admin;editor,Austin
0047,"Lee ""Sam"" Park",,
Checking the output against the rules: the name containing a comma is quoted; the inner double quotes are doubled and the whole field is quoted; the edges and node wrappers are gone; and the second row ends in two empty fields. Those two empty fields come from different things, an empty list and a null address, and the CSV cannot tell them apart. The semicolon join works here only because no role contains a semicolon.
There is also a difference between what the file stores and what an application displays. The file above stores the ID as the four characters 0012. A spreadsheet opening it may interpret that as the number 12 and show it without the leading zeros. That change happens at import, not in the file, but if the spreadsheet then saves over the CSV, the altered value becomes stored.
What flattening can drop without warning
- Errors: GraphQL can return partial data alongside an errors list. A converter that reads only the data entry will produce a clean-looking CSV with nulls where fields failed, and no sign that anything went wrong.
- Other pages: a paginated connection returns one page at a time. Converting a single response gives you that page only, unless the export step follows the cursors.
- Types: GraphQL serializes the ID type as a string, and custom scalars such as dates or JSON blobs arrive as strings or objects. After conversion, the receiving application guesses types, which can turn IDs into numbers and date strings into locale-specific dates.
- Precision: spreadsheet applications commonly store numbers as floating point with roughly 15 significant digits, so long numeric IDs can be rounded or shown in scientific notation if they are interpreted as numbers.
- Sparse fields: when a field is absent from the first record, a converter that builds headers from that record alone may omit the column entirely for every row.
- Aliases: column names come from whatever keys appear in the response, so aliased queries produce aliased headers. That is useful for readable headers, but it means the same field can appear under different names across exports.
Converting without a dedicated tool
For a known, stable query shape, a short script gives you explicit control over each flattening decision. With jq, a command-line JSON processor, the example above can be converted like this:
jq -r '["id","name","roles","address.city"],
(.data.users.edges[].node
| [.id, .name, (.roles | join(";")), .address.city])
| @csv' response.json
The @csv filter quotes every string and doubles inner quotes. One consequence is visible in the second row: the empty roles list becomes a quoted empty string, while the null city becomes a bare empty field. That keeps a trace of the difference in the raw text, although most spreadsheets display both as blank cells. jq also has an @tsv filter, which escapes tabs and line breaks inside values with backslash sequences rather than quoting them.
In Python, the standard csv module handles quoting. This version also stops if the response contains errors, rather than exporting partial data silently:
import csv, json
with open("response.json", encoding="utf-8") as f:
payload = json.load(f)
if payload.get("errors"):
raise SystemExit("Response contains errors; review before exporting")
rows = [edge["node"] for edge in payload["data"]["users"]["edges"]]
with open("users.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["id", "name", "roles", "address.city"])
for node in rows:
address = node.get("address") or {}
writer.writerow([
node["id"],
node["name"],
";".join(node["roles"]),
address.get("city", ""),
])
Opening the output file with newline set to an empty string is required by the csv module; without it, line endings can be doubled on some platforms. Both snippets hard-code the column list, which avoids the sparse-header problem but needs updating whenever the query changes.
Will the result stay readable after copying or sharing?
Copy and paste behaves differently from opening a file. Many spreadsheet applications use tab-separated text for clipboard tables, so pasted TSV often splits into cells, while pasted comma-separated text may land in a single column until it is split with an import or text-to-columns feature. This depends on the application and its settings, so test with your actual destination.
Encoding is a frequent source of garbled text. Write UTF-8. Some spreadsheet versions misread UTF-8 files that lack a byte order mark and display accented or non-Latin characters incorrectly. Adding the byte order mark can fix that, but parsers that do not strip it will read it as invisible characters at the start of the first header name, which can break lookups by column name. Choose based on who opens the file.
Delimiter expectations vary by region. In locales where the comma is the decimal separator, spreadsheets often expect semicolon-separated files. For a US audience the comma is the usual default, but files shared internationally may open as a single column.
Security is a usability concern too. Cell values that begin with an equals sign, plus, minus or at sign may be treated as formulas when the file is opened in a spreadsheet, which matters when the GraphQL data includes user-supplied text. A common mitigation is prefixing such values with an apostrophe or a space, but that alters the stored data, so apply it only to exports meant for spreadsheets, not for machine imports.
For accessibility, raw CSV read aloud by a screen reader is a stream of values and separators with no table structure. Opened in a spreadsheet with a header row, it can be navigated as a grid, but how well column headers are announced depends on the application and assistive technology combination; no such combination was tested for this review. For editing and searching, dot-notation headers keep each field in its own filterable column, while joined list cells and JSON-string cells are hard to search or edit without breaking their internal format.
Provide a plain-text equivalent when people, rather than programs, are the audience and the content is small: a short summary or list in a message, or a properly marked-up table in a document, will be more readable and more accessible than an attached CSV.
What to check in a GraphQL-to-CSV converter
- Lets you choose how lists are handled: joined, one row per item or JSON-encoded.
- Builds headers from all records, not only the first, or lets you supply a fixed column list.
- Reports or preserves the errors entry instead of discarding it.
- Follows RFC 4180 quoting for commas, quotes and line breaks.
- Keeps field order consistent with the query.
- Offers options for null handling, encoding and byte order mark.
- Processes data locally if the response contains personal or confidential information. A tool's interface or marketing claims are not evidence of how it stores or transmits pasted data; check its documented policy or avoid pasting sensitive responses.
Gaps and how to close them
No specific converter tools, spreadsheet versions or assistive technologies were tested for this review, and no measurements are reported. Behavior described as varying between applications should be confirmed in your own environment. A practical way to do that is to run a small sample through your full workflow, from query to final destination, containing a comma, a double quote, a line break, a non-ASCII character, an ID with leading zeros, a long numeric ID, a null field, an empty list and at least one error, then compare what arrives against the original JSON.