jc JSONifies the output of many CLI tools, file-types, and common strings
for easier parsing in scripts. See the Parsers section for
supported commands, file-types, and strings.
jc can also be used as a python library. In this case the returned value
will be a python dictionary, a list of dictionaries, or even a
instead of JSON:
For jc Python package documentation, use help('jc'), help('jc.lib'), or
see the online documentation.
Two representations of the data are available. The default representation uses a
strict schema per parser and converts known numbers to int/float JSON values.
Certain known values of None are converted to JSON null, known boolean
values are converted, and, in some cases, additional semantic context fields are
added.
To access the raw, pre-processed JSON, use the -r cli option or the raw=True
function parameter in parse() when using jc as a python library.
Schemas for each parser can be found at the documentation link beside each
Parser below.
There are several ways to get jc. You can install via pip, OS package
repositories, or by downloading the
correct binary for your
architecture and running it anywhere on your filesystem.
Pip (macOS, linux, unix, Windows)
pip3 install jc
OS Package Repositories
OS
Command
Debian/Ubuntu linux
apt-get install jc
Fedora linux
dnf install jc
openSUSE linux
zypper install jc
Arch linux
pacman -S jc
NixOS linux
nix-env -iA nixpkgs.jc or nix-env -iA nixos.jc
Guix System linux
guix install jc
Gentoo Linux
emerge dev-python/jc
Photon linux
tdnf install jc
macOS
brew install jc
FreeBSD
portsnap fetch update && cd /usr/ports/textproc/py-jc && make install clean
Alternatively, the "magic" syntax can be used by prepending jc to the command
to be converted or in front of the absolute path for Proc files. Options can be
passed to jc immediately before the command or Proc file path is given.
(Note: command aliases and shell builtins are not supported)
Line slicing is supported using the START:STOP syntax similar to Python
slicing. This allows you to skip lines at the beginning and/or end of the
STDIN input you would like jc to convert.
START and STOP can be positive or negative integers or blank and allow
you to specify how many lines to skip and how many lines to process.
Positive and blank slices are the most memory efficient. Any negative
integers in the slice will use more memory. Lines are counted at LF and CRLF
line endings; a lone CR does not start a new line.
For example, to skip the first and last line of the following text, you
could express the slice in a couple ways:
$ cat table.txt
### We want to skip this header ###
col1 col2
foo 1
bar 2
### We want to skip this footer ###
$ cat table.txt | jc 1:-1 --asciitable
[{"col1":"foo","col2":"1"},{"col1":"bar","col2":"2"}]
$ cat table.txt | jc 1:4 --asciitable
[{"col1":"foo","col2":"1"},{"col1":"bar","col2":"2"}]
In this example 1:-1 and 1:4 line slices provide the same output.
When using positive integers the index location of STOP is non-inclusive.
Positive slices count from the first line of the input toward the end
starting at 0 as the first line. Negative slices count from the last line
toward the beginning starting at -1 as the last line. This is also the way
Python's slicing
feature works.
Here is a breakdown of line slice options:
Slice Notation
Input Lines Processed
START:STOP
lines START through STOP - 1
START:
lines START through the rest of the output
:STOP
lines from the beginning through STOP - 1
-START:STOP
START lines from the end through STOP - 1
START:-STOP
lines START through STOP lines from the end
-START:-STOP
START lines from the end through STOP lines from the end
-START:
START lines from the end through the rest of the output
:-STOP
lines from the beginning through STOP lines from the end
:
all lines
Slurp
Some parsers support multi-item input and can output an array of results in a
single pass. Slurping works for string parsers that accept a single line of
input. (e.g. url and ip-address) To see a list of parsers that support
the --slurp option, use jc -hhh.
For example, you can send a file with multiple IP addresses (one per line) to
jc with the --slurp option and an array of results will output:
The magic syntax for /proc files automatically supports slurping of multiple
files (no need to use the --slurp option). For example, you can convert many
PID files at once:
$ jc /proc/*/status
[<multiple output objects>]
When the /proc magic syntax is used and multiple files are selected, an
additional _file field is inserted in the output so it is easier to tell what
file each output object refers to.
Finally, the --meta-out option can be used in conjunction with slurped output.
In this case, the slurped output is wrapped in an object with the following
structure:
With --meta-out, input_list contains a list of inputs (actual input strings
or /proc filenames) so you can identify which output object relates to each
input string or /proc filename.
Exit Codes
Any fatal errors within jc will generate an exit code of 100, otherwise the
exit code will be 0.
When using the "magic" syntax (e.g. jc ifconfig eth0),
jc will store the exit code of the program being parsed and add it to the jc
exit code. This way it is easier to determine if an error was from the parsed
program or jc.
Consider the following examples using ifconfig:
ifconfig exit code
jc exit code
Combined exit code
Interpretation
0
0
0
No errors
1
0
1
Error in ifconfig
0
100
100
Error in jc
1
100
101
Error in both ifconfig and jc
When using the "magic" syntax you can also retrieve the exit code of the called
program by using the --meta-out or -M option. This will append a _jc_meta
object to the output that will include the magic command information, including
the exit code.
You can specify custom colors via the JC_COLORS environment variable. The
JC_COLORS environment variable takes four comma separated string values in
the following format:
You can set the NO_COLOR environment variable to any
value to disable color output in jc. Note that using the -C option to force
color output will override both the NO_COLOR environment variable and the -m
option.
Streaming Parsers
Most parsers load all of the data from STDIN, parse it, then output the entire
JSON document serially. There are some streaming parsers (e.g. ls-s and
ping-s) that immediately start processing and outputting the data line-by-line
as JSON Lines (aka NDJSON) while
it is being received from STDIN. This can significantly reduce the amount of
memory required to parse large amounts of command output (e.g. ls -lR /) and
can sometimes process the data more quickly. Streaming parsers have slightly
different behavior than standard parsers as outlined below.
Note: Streaming parsers cannot be used with the "magic" syntax
Ignoring Errors
You may want to ignore parsing errors when using streaming parsers since these
may be used in long-lived processing pipelines and errors can break the pipe. To
ignore parsing errors, use the -qq cli option or the ignore_exceptions=True
argument with the parse() function. This will add a _jc_meta object to the
JSON output with a success attribute. If success is true, then there were
no issues parsing the line. If success is false, then a parsing issue was
found and error and line fields will be added to include a short error
description and the contents of the unparsable line, respectively:
Most operating systems will buffer output that is being piped from process to
process. The buffer is usually around 4KB. When viewing the output in the
terminal the OS buffer is not engaged so output is immediately displayed on the
screen. When piping multiple processes together, though, it may seem as if the
output is hanging when the input data is very slow (e.g. ping):
$ ping 1.1.1.1 | jc --ping-s | jq
<slow output>
This is because the OS engages the 4KB buffer between jc and jq in this
example. To display the data on the terminal in realtime, you can disable the
buffer with the -u (unbuffer) cli option:
Note: Unbuffered output can be slower for large data streams.
Using Streaming Parsers as Python Modules
Streaming parsers accept any iterable object and return an iterable object
allowing lazy processing of the data. The input data should iterate on lines
of string data. Examples of good input data are sys.stdin or
str.split('\n').
To use the returned iterable object in your code, simply loop through it or
use the next()
builtin function:
import jc
result = jc.parse('ls_s', ls_command_output.split('\n'))
for item in result:
print(item["filename"])
Parser Plugins
Parser plugins may be placed in a jc/jcparsers folder in your local
"App data directory":
Parser plugins are standard python module files. Use the
jc/parsers/foo.py
or jc/parsers/foo_s.py (streaming)
parser as a template and simply place a .py file in the jcparsers subfolder.
Any dependencies can be placed in the jc folder above jcparsers and can
be imported in the parser code.
Parser plugin filenames must be valid python module names and therefore must
start with a letter and consist entirely of alphanumerics and underscores.
Local plugins may override default parsers.
For best results set the locale environment variables to C or
en_US.UTF-8 by modifying the LC_ALL variable:
$ LC_ALL=C date | jc --date
You can also set the locale variables individually:
$ export LANG=C
$ export LC_NUMERIC=C
On some older systems UTF-8 output will be downgraded to ASCII with \u
escape sequences if the C locale does not support UTF-8 encoding.
Timezones
Some parsers have calculated epoch timestamp fields added to the output. Unless
a timestamp field name has a _utc suffix it is considered naive. (i.e. based
on the local timezone of the system the jc parser was run on).
If a UTC timezone can be detected in the text of the command output, the
timestamp will be timezone aware and have a _utc suffix on the key name.
(e.g. epoch_utc) No other timezones are supported for aware timestamps.
Line Endings
jc passes input to the parser without translating line endings, whether it
comes from STDIN, a "magic" command, or a /proc file. All line-based
parsers split lines at LF and CRLF line endings only, so other characters that
can appear inside a value, such as a lone CR, form feed, or Unicode line separator, stay
part of that line. Parsers for file formats that can use CR-only line endings (csv,
hosts, jar-manifest, and m3u) also accept a lone CR as a line ending.
Streaming parsers split STDIN lines the same way (LF and CRLF only). Bytes
in STDIN that are not valid UTF-8 are shown as backslash escapes (e.g.
\xff) instead of stopping the parser.
Use In Other Shells
jc can be used in most any shell. Some modern shells have JSON deserialization
and filtering capabilities built-in which makes using jc even more convenient.
For example, the following is possible in NGS
(Next Generation Shell):
This runs jc, parses the output JSON, and assigs the resulting data structure
to a variable in a single line of code.
For more examples of how to use jc in other shells, see this
wiki page.
Compatibility
Some parsers like dig, xml, csv, etc. will work on any platform. Other
parsers that convert platform-specific output will generate a warning message if
they are run on an unsupported platform. To see all parser information,
including compatibility, run jc -ap.
You may still use a parser on an unsupported platform - for example, you may
want to parse a file with linux lsof output on a macOS or Windows laptop. In
that case you can suppress the warning message with the -q cli option or the
quiet=True function parameter in parse():