Skip to content
Tutorials Center
My learning

Topics

Lesson 156 of 156 ยท Practice and Review

JSON Recipes: Pretty Print, CSV and HTML Tables

Practical JSON recipes: pretty print, convert JSON to CSV and back, build an HTML table, swap keys and values, edit attributes, handle dates and send JSON.

You already know JSON.stringify() and JSON.parse() from JSON. This lesson is a cookbook for the jobs that come up again and again once real data arrives: show it nicely, convert it to a spreadsheet format, put it in a table, reshape it, fix its dates, check it for keys and send it to a server.

Every recipe is a small function you can copy, and every example runs in the console below it. Because JSON is plain text that becomes plain objects, nearly all of these recipes are ordinary object and array work with two built-ins at the edges.

Pretty print and compact

JSON.stringify(value, replacer, space) takes a third argument that controls indentation. A number means "this many spaces", a string means "use this text for each level".

JS Pretty print, compact and sorted keys

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

No output.

Pretty printing is for people; send the compact form over the network. Sorted keys are handy for comparing two documents or for stable files in version control.

JSON to CSV and back

CSV is a table as text: one line per row, commas between cells. The only tricky part is that a cell containing a comma, a quote or a line break must be wrapped in double quotes, with inner quotes doubled.

JS Array of objects to CSV and back

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

No output.

Notice that the round trip gives you back strings only: CSV has no types, so "42" stays text until you convert it with Number(). For huge files or exotic dialects (other separators, byte-order marks) use a dedicated library; this version is right for small, well-formed data.

JSON to an HTML table

When you put data in HTML, treat every value as text, never as markup. Creating the cells with textContent makes the table safe even if the data contains <script> (see XSS and Safe DOM Updates).

Build a table from an array of objects

The <b>Pen</b> row shows the point: the tags appear as text. The missing price for the eraser becomes an empty cell because the column list is the union of all keys.

Swap keys and values, and rename keys

Object.entries() and Object.fromEntries() turn an object into pairs and back, so reshaping is a one-liner on the pairs in the middle.

JS Swap and rename keys

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

No output.

Swapping only works when the values are unique and usable as keys (strings or symbols; other values are converted to strings).

Add, change and remove attributes

Treat parsed JSON like any other data and prefer immutable updates, which create new objects and leave the original alone. That makes changes easy to compare, undo and test.

JS Immutable add, modify and remove

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

No output.

See Copying Objects for when a shallow copy is enough and when you need structuredClone().

Dates in JSON

JSON has no date type. JSON.stringify() turns a Date into its ISO 8601 string (via toJSON()), and JSON.parse() gives you that string back, not a Date. A reviver converts the right fields on the way in.

JS Round-tripping dates

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

No output.

Always store dates in UTC ISO form and convert to the viewer's time zone only when displaying. The Dates lesson explains why.

Check whether a key exists

There are three questions people mix up: "is the key there at all?", "is the value defined?" and "is it truthy?".

JS Checking keys safely

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

No output.

Use Object.hasOwn() to ask whether a key exists, and ?. with ?? to read a value that may be absent. Remember that ?? keeps 0, "" and false as real values.

Send JSON to a server

To post JSON you set the Content-Type header, serialize the body and read the answer with response.json(). The sandbox cannot call real servers, so this example builds a Request object offline and reads it back, which shows exactly what would be sent.

JS What a JSON request looks like

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

No output.

In a real page, pass the same options to fetch(), check response.ok before calling response.json(), and handle a body that is not valid JSON with try/catch. Fetch covers the whole flow.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does JSON.stringify(obj, null, 2) do?

    The third argument sets the indentation. A number means that many spaces per level; it does not change which properties are included or their order.
  2. 2. Why should a CSV writer wrap some cells in double quotes?

    Commas separate cells and line breaks separate rows, so cells that contain them are quoted, and quotes inside are doubled.
  3. 3. After JSON.parse(), what is the type of a field that was a Date before JSON.stringify()?

    Date.prototype.toJSON() makes an ISO string, and JSON has no date type, so parsing gives a string unless you use a reviver.
  4. 4. Which check tells you a key exists on an object even when its value is 0 or null?

    Object.hasOwn() tests for the key itself. Truthiness tests treat 0, "" and null as missing.

Summary

  • JSON.stringify(value, null, 2) pretty prints; a replacer can sort keys or drop properties.
  • CSV conversion needs quoting for commas, quotes and line breaks, and CSV values come back as strings.
  • Build HTML tables with textContent, not string concatenation, so data can never become markup.
  • Object.entries() / Object.fromEntries() swap and rename keys; spread and rest give immutable add, change and remove.
  • Dates become ISO strings in JSON; use a reviver to turn them back into Date objects.
  • Use Object.hasOwn() for key checks and ?./?? for optional reads.
  • Send JSON with a Content-Type: application/json header and a stringified body.

Next: Object Recipes.