Quick json and sql string formatting
When working with long jsons or sql queries I keep opening the text editor and using its json and sql formatters. This feels slow, specially for sharing the strings on the chat. To improve the speed of this I created a couple of commands which can I call from rofi. Alternatively, a keyboard shortcut can be created.
The idea is to select and copy a string (either json or sql query) and pressing a short combination of keys, the string in the clipboard will be formatted.
For these we need:
- A clipboard manager program, such as xclip
- A json formatter, such as jq
- A sql formatter, such as sqlfmt
What the script should do:
- Select latest entry in clipboard
- Run string formatter
- Put the output in the clipboard
Formatting json string
xclip -o | jq . | xclip -sel clip
Formatting sql query
xclip -sel clip <<< "$(xclip -o | sqlfmt - --single-process -q)"
The commands are slightly different. This was done in purpose since I wanted to test string substitution in bash. The command could be rewritten as:
xclp -o | sqlfmt - --single-process -q | xclip -sel clip
Testing
To test:
- Copy the command into the terminal
- Copy the input test data (ctrl + c)
- Run the command in the terminal
- Paste into a text editor (ctrl + v)
Json test data:
[
{"name":"John", "email":"John@mail.com"},
{"name":"Doe", "email":"Doe@mail.com"}
]
Json output:
[
{
"name": "John",
"email": "John@mail.com"
},
{
"name": "Doe",
"email": "Doe@mail.com"
}
]
Sql input data:
SELECT first_name, last_name FROM users;
Sql output data:
select first_name, last_name
from users
;