Created
March 5, 2023 09:43
-
-
Save baysideengineer/5d21d78ac98d01850e119648d1c68df3 to your computer and use it in GitHub Desktop.
Shell script for adding an increasing ID as a first key of an object inside an JSON array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/zsh | |
FILE_PATH="data.json" | |
DATA=$(cat "$FILE_PATH") | |
REVERSE_ORDER=$(jq 'reverse' <<<"$DATA") | |
DATA_LENGTH=$(echo "$REVERSE_ORDER" | jq '. | length') | |
for ((INDEX = 0; INDEX < DATA_LENGTH; INDEX++)); do | |
REVERSE_ORDER=$(jq --argjson id "$INDEX" '.['"$INDEX"'] += { "id": ($id+1) }' <<<"$REVERSE_ORDER") | |
done | |
SORT_KEYS=$(jq '[.[] | { id, keyTwo, keyThree, keyFour }]' <<<"$REVERSE_ORDER") | |
echo "$SORT_KEYS" >"$FILE_PATH" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment