Skip to content

Instantly share code, notes, and snippets.

@svasquezm
Created March 12, 2024 11:50
Show Gist options
  • Save svasquezm/a97fa2f2bc8b77ba2e9fe0dd58c35c83 to your computer and use it in GitHub Desktop.
Save svasquezm/a97fa2f2bc8b77ba2e9fe0dd58c35c83 to your computer and use it in GitHub Desktop.
Bash script to format JSON copied text into a JSONArray file
### Validate a clipboard copied JSONArray. If the JSON is not an Array, this
### script put within to one.
### Usage
### 1. Copy a JSON string
### 2. Run this script ./putme_on_array.sh
### 3. If success, can happen
### 3.1 If JSON is a JSONObject, then the script will write a ~/json_array.json file with
### the result in your clipboard
### 3.2 Otherwise the script will print an error
#!/bin/bash
copiedtext=$(pbpaste)
echo $copiedtext | json_pp | grep "" > /dev/null
clipboard_result=$?
# JSON is correctly formatted?
if [ $clipboard_result = 0 ]; then
# Check if copied text is within an array
firstchar="$(printf '%c' "$(pbpaste)")"
lastchar=`echo $copiedtext | sed -E 's/.*(.)/\1/'`
if [ $firstchar = "[" ] && [ $lastchar = "]" ]; then
echo "Its a JSON Array!"
formatted_text=`echo "${copiedtext}" | json_pp`
echo $formatted_text >> ~/json_array.json
else
echo "Is not a JSON Array, converting into an array..."
formatted_text=`echo "[${copiedtext}]" | json_pp`
echo $formatted_text | pbcopy
echo $formatted_text >> ~/json_array.json
fi
echo "Done!"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment