DEV Community

Pavol Z. Kutaj
Pavol Z. Kutaj

Posted on

1

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.

API Trace View

Struggling with slow API calls?

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

đź‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay