Clipboard to JSON string

2025-10-20

The other day I needed to grab the content of my clipboard and turn it into a valid JSON string. The content contained a bunch of new lines and symbol that you need to escape.

I knew jq could do this but I had a hard time figuring out what combination of flags I needed to the it to work.

After looking at the manual, I felt like -R was the right flag for the job, so I did pbpaste | jq -R ., but I was disappointed. Each new line was turned into a separate JSON String. For example:

hello,
how are you?

Was turned into:

"hello,"
"how are you?"

This is close, not exactly what I want. A few searches later and I had it:

pbpaste | jq -Rs .

Gave me:

"hello,\nhow are you?"

In hindsight, this is obvious because if you read the entry for -R carefully, all the way to the end, you can read (emphasis mine):

–raw-input / -R: Don’t parse the input as JSON. Instead, each line of text is passed to the filter as a string. If combined with –slurp, then the entire input is passed to the filter as a single long string.