To read JSON from a file with jq, you pass the filename as an argument after your filter, or use the --slurpfile option to load an entire file into a variable. For example, jq '.name' data.json reads data.json and outputs the value of the name field. This is the fundamental way jq consumes file input: it treats each file as a stream of JSON values and applies the filter to each one.
How jq Reads Files
jq is a command-line JSON processor. When you run jq, it reads JSON from standard input by default, but you can also provide one or more filenames as arguments. jq processes each file in sequence, applying the filter to every JSON value it encounters. By default, jq expects the input to be a stream of JSON values, not necessarily a single array. If the file contains multiple JSON objects separated by whitespace, jq will process each one individually. For example, a file with two objects {"a":1}{"a":2} will produce two outputs when filtered with .a. If the file contains a single JSON array, jq treats the whole array as one value. This distinction matters when you want to aggregate results across multiple values.
jq also supports reading from multiple files at once. You can list several filenames, and jq will process them in order. The --slurp (or -s) option changes this behavior: it reads all input values from all files into a single array before applying the filter. This is useful when you need to treat the entire input as one array, regardless of how many JSON values it contains.
Basic Syntax and Examples
The general syntax is jq [options] filter [files...]. If no files are given, jq reads from stdin. Here are some common examples:
jq '.' data.json— pretty-prints the entire JSON content ofdata.json.jq '.users[0].name' data.json— extracts the name of the first user.jq -r '.items[] | .id' data.json— outputs each item's id as raw text (without quotes).jq -s 'add' file1.json file2.json— slurps both files into an array and sums the numeric values (if the files contain numbers or arrays).
Note that jq filters are applied to each JSON value in the input stream. If your file contains a single top-level array, the filter sees that array as one value. If it contains multiple objects, the filter sees each object separately. Understanding this stream behavior is key to writing correct filters.
Using --slurpfile and --argfile
Sometimes you need to read a file into a variable rather than as the main input stream. jq provides --slurpfile and --argfile for this purpose. --slurpfile name file reads the file and binds its parsed JSON content to the variable $name as an array of all JSON values in the file. --argfile name file binds the first JSON value in the file to $name (deprecated in newer jq versions in favor of --slurpfile and --rawfile). For example, jq --slurpfile config config.json '.settings + $config[0]' data.json merges settings from config.json into the main input. This is handy for combining data from multiple sources without altering the main input stream.
There is also --rawfile name file, which reads the file as a raw string (not parsed as JSON) and binds it to $name. This is useful when you need to include text content, such as a template or a plain text file, inside your JSON output.
Common Pitfalls and How to Avoid Them
Several issues commonly trip up jq users when reading from files:
- Multiple JSON values in one file: If your file contains concatenated JSON objects (e.g., from a log), jq will process each separately. Use
--slurpto combine them into an array if you need to treat them as a single unit. - Invalid JSON: jq will report a parse error and stop. Ensure the file is valid JSON. Tools like
jq empty file.jsoncan validate syntax without outputting anything. - Large files: jq streams input, so it can handle large files without loading everything into memory, unless you use
--slurpor certain filters that require full context. For very large files, consider using--streamto parse incrementally. - File encoding: jq expects UTF-8 encoded JSON. Files with other encodings may cause errors or incorrect output.
- Missing files: jq will error if a file does not exist. Use shell globbing or check file existence beforehand.
Another common misconception is that jq modifies files in place. jq does not edit files; it only reads and outputs. To save output, redirect to a new file (e.g., jq '.' data.json > formatted.json).
Reading from Standard Input vs. Files
jq can read from stdin, which is useful in pipelines. For example, cat data.json | jq '.name' is equivalent to jq '.name' data.json. However, when using stdin, you cannot easily provide multiple files or use file-specific options like --slurpfile (though you can still use --slurp on stdin). Reading from files is generally more convenient for repeated operations and allows jq to handle multiple inputs seamlessly. In scripts, it's common to pass filenames as arguments to avoid issues with shell redirection and to leverage jq's built-in file handling.
Frequently Asked Questions
How do I read a JSON file with jq and output a specific field?
Use jq '.fieldname' file.json. For nested fields, use dot notation, e.g., .user.name. If the field is an array element, use an index like .items[0].
What is the difference between --slurp and --slurpfile?
--slurp (or -s) reads all input values from all files into a single array that becomes the main input. --slurpfile reads a file into a variable as an array, leaving the main input stream unchanged. Use --slurpfile when you need to reference another file's content within your filter.
Can jq read from a file and write back to the same file?
No, jq does not support in-place editing. You must redirect output to a temporary file and then move it, e.g., jq '.' file.json > tmp.json && mv tmp.json file.json.
Why does jq output multiple lines when my file has one JSON object?
If your file contains multiple JSON values (e.g., newline-delimited JSON), jq processes each separately and outputs each result on its own line. Use --slurp to combine them into an array, or adjust your filter to handle the stream.
How do I handle files with a BOM (byte order mark)?
jq may fail on files with a BOM. You can strip the BOM using a tool like sed or dos2unix before passing to jq, or use --rawfile and process the string manually if needed.
Alternatives and Related Tools
While jq is the de facto standard for JSON processing on the command line, other tools exist. fx is a JavaScript-based JSON viewer with interactive features. gron flattens JSON into greppable assignments. yq is similar to jq but for YAML (and can handle JSON as a subset). For programming languages, libraries like Python's json module or JavaScript's JSON.parse offer programmatic access. jq's advantage is its concise filter language and streaming capability, making it ideal for quick command-line tasks and shell scripts. It is available for Linux, macOS, Windows, and BSD, and can be installed via package managers. Its filter language is Turing-complete, allowing complex transformations, but most users only need a small subset of its features for everyday file reading and extraction.