DEV Community

Pavol Z. Kutaj
Pavol Z. Kutaj

Posted on

How to use jq for URI encoding

USECASE

The aim of this page📝 is to explain how to URI-encode a password in a shell script using the jq tool. Note that — for me surprisingly — this usecase has nothing to do with JSON manipulation and makes jq even more versatile.

Introduction

URL-encoding ensures that passwords and other data are safely transmitted over the web. Let's delve into a shell script example where we utilize the versatile jq tool for this task.

Code Snippet

The shell script snippet in question:

password="<3@prax4ce>"
password_uri=$(echo -n "${password}" | jq -sRr @uri)
echo $password_uri
Enter fullscreen mode Exit fullscreen mode

Output:

%3C3%40prax4ce%3E
Enter fullscreen mode Exit fullscreen mode

Breakdown of the Command

Let's dissect this line of code:

  • echo -n "${password}": This command outputs the value of the password variable without appending a newline character.
  • |: This is a pipe, used to pass the output of the echo command to the next command.
  • jq -sRr @uri:
    • -s: Slurps the input into a single string, allowing jq to handle it all at once.
    • -R: Reads the input as raw strings instead of JSON.
    • -r: Outputs raw strings, avoiding JSON encoding.
    • @uri: Encodes the input string (our password) as a URI component.

Top comments (0)