Jq: Difference between revisions

From wikinotes
Line 31: Line 31:
echo '["a", "b", "c"]' | jq '.[1]'                  # "b"
echo '["a", "b", "c"]' | jq '.[1]'                  # "b"
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Basics -->
</blockquote><!-- Basics -->
== Filters ==
<blockquote>
<syntaxhighlight lang="bash">
jq '.'        # obj
jq '.one'    # obj["one"]
jq '.one?'    # obj["one"] (but no error if not exist)
jq '.one.two' # obj["one"]["two"]
jq '.[1]'    # obj[1]
jq '.[5:10]'  # list-items 5-10
</syntaxhighlight>
</blockquote><!-- Filters -->
== Expressions ==
<blockquote>
Selections within <code>()</code> are evaluated as expressions
</blockquote><!-- Expressions -->
== Operators ==
<blockquote>
Used in expressions
<syntaxhighlight lang="bash">
+
-
*
/
%
</syntaxhighlight>
</blockquote><!-- Operators -->
== Transform ==
<blockquote>
You can compose new objects from the input object.
<syntaxhighlight lang="bash">
jq '{"fullname": (.firstname + .lastname)}'
</syntaxhighlight>
</blockquote><!-- Transform -->


== Comments ==
== Comments ==

Revision as of 02:51, 29 August 2021

parse json on the commandline.

Documentation

official docs https://stedolan.github.io/jq/manual/
basic filters docs https://stedolan.github.io/jq/manual/#Basicfilters
homepage https://stedolan.github.io/jq/

Usage

Basics

# print w/ syntaxhighlighting
echo '{"one": 1, "two": {"a": "A"}}' | jq

# get key ["one"]
echo '{"one": 1, "two": {"a": "A"}}' | jq '.one'    # 1

# get nested-key ["two"]["a"]
echo '{"one": 1, "two": {"a": "A"}}' | jq '.two.a'  # "A"

# get list item at index 1
echo '["a", "b", "c"]' | jq '.[1]'                  # "b"

Filters

jq '.'        # obj
jq '.one'     # obj["one"]
jq '.one?'    # obj["one"] (but no error if not exist)
jq '.one.two' # obj["one"]["two"]
jq '.[1]'     # obj[1]
jq '.[5:10]'  # list-items 5-10

Expressions

Selections within () are evaluated as expressions

Operators

Used in expressions

+
-
*
/
%

Transform

You can compose new objects from the input object.

jq '{"fullname": (.firstname + .lastname)}'

Comments

Neither json nor jq support comments.
It's hacky, but you could pre-process the object to strip them, however.

echo '{
  // syntax-highlight as javascript

  "local_path": "/home/you", // your home dir

  // a network path
  "netwk_path": "//10.1.0.5/music"
}' \
  | sed 's?//[^"]*$??'
  | jq '.one'