Skip to content

Instantly share code, notes, and snippets.

@dotemacs
Last active February 2, 2022 15:12
Show Gist options
  • Save dotemacs/6c9185cca3cf59486b55471b1e965ed5 to your computer and use it in GitHub Desktop.
Save dotemacs/6c9185cca3cf59486b55471b1e965ed5 to your computer and use it in GitHub Desktop.

jq to jet

Implement all the examples from jq tutorial in jet:

https://stedolan.github.io/jq/tutorial/

Fetch the output and pretty print it

In jq

curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.'

In jet

curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jet -p

Fetch just the first commit

In jq

curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.[0]'

In jet

curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jet -i json -o json -f '#(first %)'

or

curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jet -i json -o json -q 'first'

Get just the message and the committer name

So that it looks like this:

{
  "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",
  "name": "Stephen Dolan"
}

In jq

curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.[0] | {message: .commit.message, name: .commit.committer.name}'

In jet

curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | \
jet -p -i json -o json -k --query 'first' -f '#(hash-map :message (get-in % [:commit :message]) :name (get-in % [:commit :committer :name]))'

Extract the message and the committer name from all the commits

In jq

jq '.[] | {message: .commit.message, name: .commit.committer.name}

In jet

jet -p -i json -o json -k -f '#(map (fn [x] (hash-map :message (get-in x [:commit :message]) :name (get-in x [:commit :committer :name]))) %)'

Add the parent commit URL(s) to the above

In jq

jq '[.[] | {message: .commit.message, name: .commit.committer.name, parents: [.parents[].html_url]}]'

In jet

jet -p -i json -o json -k -f \
'#(map
   (fn [x]
     (hash-map
       :message (get-in x [:commit :message])
       :name (get-in x [:commit :committer :name])
       :parents (mapv :html_url (:parents x)))) %)'

or

jet -p -i json -o json -k -f /tmp/fn.clj

where /tmp/fn.clj contains the function:

#(map
   (fn [x]
     (hash-map
       :message (get-in x [:commit :message])
       :name (get-in x [:commit :committer :name])
       :parents (mapv :html_url (:parents x)))) %)

Other useful jet commands

Format a JSON file

To print out a JSON file as EDN, with keywordized keys:

jet -i json -o edn -k -p < file.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment