jq · lesson 23 of 32 · Tables & lookups

Quoting & escaping

Values with commas, quotes or line breaks need care. @csv puts every string in double quotes and doubles any quote inside it; @tsv quotes nothing and writes tabs, line breaks and backslashes as escapes instead.

Examples

Example 1CSV: quotes around strings, doubled quotes inside

Document

[
  { "name": "Smith, Jo", "note": "said \"hi\"" },
  { "name": "Ada", "note": "two\nlines" },
  { "name": "Tab\tman", "note": "C:\\temp" }
]

Query

.[] | [.name, .note] | @csv
  1. .[] Each record in turn.
  2. [.name, .note] Two cells per row.
  3. @csv Strings go in double quotes, and the " in said "hi" becomes "". A comma or a line break inside the quotes stays as it is: it can't be taken for the end of the cell.

Result

"Smith, Jo","said ""hi"""
"Ada","two
lines"
"Tab	man","C:\temp"

Try it in the playground

Example 2TSV: no quotes, escapes instead

Document

[
  { "name": "Smith, Jo", "note": "said \"hi\"" },
  { "name": "Ada", "note": "two\nlines" },
  { "name": "Tab\tman", "note": "C:\\temp" }
]

Query

.[] | [.name, .note] | @tsv
  1. .[] Each record in turn.
  2. [.name, .note] The same two cells.
  3. @tsv Cells are joined with tabs and never quoted. A tab inside a value is written \t, a line break \n and a backslash \\, so a record always stays on one line.

Result

Smith, Jo	said "hi"
Ada	two\nlines
Tab\tman	C:\\temp

Try it in the playground

Example 3Only an array makes a row

Document

[
  { "name": "Smith, Jo", "note": "said \"hi\"" },
  { "name": "Ada", "note": "two\nlines" },
  { "name": "Tab\tman", "note": "C:\\temp" }
]

Query

try (.[0] | @csv) catch .
  1. try ( Run what is inside the parentheses; if it fails…
  2. .[0] | @csv …as it does here, because the first record is an object and @csv wants an array…
  3. catch . …hand back the error message instead (. is the message).

Result

"object ({\"name\":\"Smith, Jo\",\"not...) cannot be csv-formatted, only an array can be"

Try it in the playground

Good to know

  • In both formats a number or a boolean is written bare (3, true) and null is an empty cell.
  • A tool that reads TSV should turn \t, \n, \r and \\ back into the characters they stand for.

About jsonquery

Query, format and learn JSON with jq, JSONPath, JMESPath and JSON Pointer. It is the engine of the desktop app, run in your browser.

Engine
The desktop app’s, compiled to WebAssembly
Licence
MIT (the engine and the app)
Source
GitHub
Contact
The contact form (private)
Public issues
GitHub
Legal
Privacy policy

Known limitations: a file over 10 MB opens read-only and one over 512 MB does not open here; the desktop app has no such limit.