Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 · JSON

Converting JSON to and from CSV, Map, Set, Blob and Spreadsheets

Move data between JSON and other shapes: Map and Set, CSV with correct quoting, Blob and File objects, downloads, and spreadsheet-friendly exports and imports.

JSON rarely lives alone. A report has to open in a spreadsheet, so you need CSV. A cache keeps its entries in a Map, so you need to save and restore it. A user drops a .json file on your page, and you have a File object to read. A download button must turn your data into a file. Each of these is a conversion between JSON text and some other shape, and each has details that are easy to get wrong.

This lesson collects the conversions you will actually need: Map and Set, JSON to CSV and back (with quoting done properly), Blob and File, downloads, and spreadsheets. If you have not read Revivers, Replacers and toJSON, skim it first, because the hooks there are the machinery behind several of these conversions.

Conversions in this lesson

Map and Set Arrays and objects in between.
CSV Rows, quotes and commas.
Blob and File Read, write and download.
Spreadsheets CSV for Excel; libraries for xlsx.
1 / 2

Map and Set to JSON and back

JSON.stringify(new Map()) gives {}, which loses every entry silently. The simple fix is to convert to a plain shape and back:

Type Out Back
Map with string keys Object.fromEntries(map) new Map(Object.entries(obj))
Map with any keys [...map] (array of [key, value] pairs) new Map(pairs)
Set [...set] new Set(array)

Use the array of pairs form when keys are not strings (numbers, objects, dates), because object keys always become strings. Use the object form when the Map is really a dictionary and you want readable JSON.

JS Map and Set round trips

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The third group of lines shows the classic trap: after the object round trip lossy.get(1) is undefined, because the key is now the string "1".

JSON to CSV

CSV (comma-separated values) is the lingua franca of spreadsheets. It looks trivial: join values with commas, join rows with newlines. The trouble starts when a value contains a comma, a double quote or a newline. The rules (from RFC 4180) are:

  1. A field containing a comma, a double quote or a line break must be wrapped in double quotes.
  2. A double quote inside a quoted field is written twice ("").
  3. Rows end with \r\n (many tools accept \n).
  4. The first row is usually a header with the column names.

You also need to decide what to do with null, undefined, nested objects and arrays. A common choice is an empty field for null, and JSON.stringify of the value (then quoted) for nested data.

There is one more danger: CSV injection. A spreadsheet treats a cell starting with =, +, - or @ as a formula. If a user can put =HYPERLINK(...) into your data, opening your export in Excel may run it. When exporting data typed by users, prefix such cells with a single quote or a space.

JS A correct JSON to CSV converter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check the second data row in the output: the name contains double quotes (doubled), and the note spans two lines inside one quoted cell. The third row's formula is neutralised with a leading apostrophe.

CSV to JSON

Parsing CSV with split(",") breaks as soon as a quoted field contains a comma. A correct parser reads character by character and tracks whether it is inside quotes. The small version below handles quotes, doubled quotes, embedded newlines and \r\n. For huge or messy files use a library such as Papa Parse, but it helps to know what such a library does.

JS A small CSV parser

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that every value comes back as a string. CSV has no numbers, booleans or null; a CSV import always needs an explicit conversion step, ideally with validation (see JSON Schema for the idea). Also note that a leading zero in a zip code or phone number survives only if you keep it as a string.

Blob and File

A Blob is a chunk of raw data with a MIME type. A File is a Blob that also has a name and a modification time. Both convert easily to and from JSON text.

  • JSON to Blob: new Blob([JSON.stringify(data, null, 2)], { type: "application/json" }).
  • Blob or File to JSON: JSON.parse(await file.text()), or await new Response(blob).json().
  • Size: blob.size is the length in bytes, not characters, so a string with emoji is larger than its .length.
JS JSON to Blob and back

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The bytes are greater than the character count because é, è and û take two bytes each in UTF-8. Always validate files you read: the extension and the MIME type come from the user, not from the content.

Downloading JSON

To let the user save a file, create an object URL for the Blob and click a temporary link. This needs a real page, so the code below is read-only in this lesson:

JavaScript
function downloadJson(data, filename) {
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.append(link);
  link.click();
  link.remove();
  URL.revokeObjectURL(url);   // free the memory
}

Always call URL.revokeObjectURL() afterwards; each object URL keeps its Blob in memory until you do (or until the page closes). The same function works for CSV with the type text/csv;charset=utf-8. If the file must open correctly in older versions of Excel with accented characters, put a byte-order mark ("\uFEFF") in front of the CSV text.

Reading goes the other way: an <input type="file"> gives input.files[0], and await file.text() returns the content, after which you parse and validate it. For larger files, read the first bytes with file.slice(0, 1024).text() to sniff the format before loading everything.

JSON and spreadsheets

Spreadsheets give you two practical routes.

  1. CSV. Easiest and universal. Excel, Google Sheets and LibreOffice all open it. Good for flat tables; poor for nested data and types.
  2. Real workbooks (.xlsx). For multiple sheets, formatting or typed cells, use a library. The best-known browser and Node library is SheetJS, which can turn an array of objects into a sheet and read a workbook back into JSON:
JavaScript
// SheetJS (read-only illustration; install the library to run it)
const sheet = XLSX.utils.json_to_sheet(people);
const book = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(book, sheet, "People");
XLSX.writeFile(book, "people.xlsx");

// and back
const loaded = XLSX.read(await file.arrayBuffer());
const rows = XLSX.utils.sheet_to_json(loaded.Sheets[loaded.SheetNames[0]]);

The idea is always the same: array of flat objects in, sheet out; sheet in, array of flat objects out. Flatten nested data first (address.city becomes a column named address_city), and decide how dates travel: as ISO strings in JSON and as real date cells in a workbook.

Quick checklist

  • Round-trip your conversion in a test: convert, convert back, compare.
  • Quote CSV fields correctly, and guard exports against formula injection.
  • Convert types explicitly after a CSV import; the file has only strings.
  • Count bytes with Blob.size, not string.length, when limits are in bytes.
  • Revoke object URLs and never trust a file's extension.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does JSON.stringify(new Map([["a", 1]])) return?

    A Map has no enumerable own properties, so it becomes an empty object. Convert it with Object.fromEntries or [...map] first.
  2. 2. Why is value.split(",") a bad CSV parser?

    A correct parser must track whether it is inside a quoted field.
  3. 3. How is a double quote written inside a quoted CSV field?

    RFC 4180 doubles the quote: "He said ""hi""" represents He said "hi".
  4. 4. After parsing a CSV file, what is the type of every value?

    CSV is plain text, so every cell is a string until your code converts it.
  5. 5. What should you do after you finish a download that used URL.createObjectURL(blob)?

    An object URL keeps the Blob alive until you revoke it or the document unloads.

Summary

  • Map and Set need converting (Object.fromEntries, [...map], [...set]); use pairs when keys are not strings.
  • CSV needs quoting for commas, quotes and newlines, doubled quotes inside fields, and protection against spreadsheet formulas; imports give back strings only.
  • Blob and File convert with JSON.stringify into a Blob and await file.text() plus JSON.parse back; downloads use object URLs that you revoke.
  • For real spreadsheets use CSV for simple tables, or a library such as SheetJS for .xlsx, always flattening nested data first.

Next: how JSON compares to other data formats in JSON Syntax and Data Types, or put JSON into web pages with JSON-LD and Embedding JSON in HTML.