Skip to content

Instantly share code, notes, and snippets.

@stella3d
Last active January 19, 2023 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stella3d/1635316c38d78113580824a86b7c4991 to your computer and use it in GitHub Desktop.
Save stella3d/1635316c38d78113580824a86b7c4991 to your computer and use it in GitHub Desktop.
`cjq` - pretty print JSON requests in your shell
# fetch remote JSON and pretty-print it
cjq() {
curl -H "Content-Type: application/json" $2 $3 $4 $5 $1 | jq
}

Setup

  • make sure you have jq installed - https://stedolan.github.io/jq/
  • add the contents of this .zshrc to your preferred shell config file, like .zshrc / .bashrc

Basic GET Requests

parameter $1 is the URL you want to request, and is non-optional for all usage of cjq.

here's an example of use:

fetch data about stablecoin market cap by chain

cjq https://stablecoins.llama.fi/stablecoinchains

outputs like (truncated to first & last entries)

[
  {
    "gecko_id": null,
    "totalCirculatingUSD": {
      "peggedUSD": 582797851.7366451,
      "peggedEUR": 970807.306137718,
      "peggedVAR": 45320.653749717705
    },
    "tokenSymbol": null,
    "name": "Optimism"
  },
  {
    "gecko_id": "ethereum-pow-iou",
    "totalCirculatingUSD": {
      "peggedUSD": 936.3412050925947
    },
    "tokenSymbol": "ETHW",
    "name": "EthereumPoW"
  }
]

Options / POSTing

parameters $2 - $5 are optional, and passed to curl as options before the url.

If you want to support more options, add more param numbers to the series after 5.

you can use this to easily support POST operations, like:

send {"a": 2} to Postman's echo server

cjq https://postman-echo.com/post -d '{"a":2}'

outputs

{
  "args": {},
  "data": {
    "a": 2
  },
  "files": {},
  "form": {},
  "headers": {
    "x-forwarded-proto": "https",
    "x-forwarded-port": "443",
    "host": "postman-echo.com",
    "x-amzn-trace-id": "Root=1-63c9a6a9-0c50ac3e51611ff20a770a1b",
    "content-length": "7",
    "user-agent": "curl/7.85.0",
    "accept": "*/*",
    "content-type": "application/json"
  },
  "json": {
    "a": 2
  },
  "url": "https://postman-echo.com/post"
}

Possible Improvements?

things i haven't done because my use doesn't need

  • you could make this pass options to jq
  • maybe name the parameters so it has a better way of dealing with optional params, rather than putting them all after required ones like $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment