-
-
Save mcwalrus/f5b31a66d55a9895d49a430f60c1254f to your computer and use it in GitHub Desktop.
json unix formatter
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/bash | |
| if ! command -v jq &> /dev/null; then | |
| echo "Error: jq is not installed. Please install jq to use this script." | |
| exit 1 | |
| fi | |
| convert_timestamp() { | |
| if [[ "$OSTYPE" == "darwin"* ]]; then | |
| date -r "$1" -u "+%Y-%m-%d %H:%M:%S UTC" | |
| else | |
| date -u -d "@$1" "+%Y-%m-%d %H:%M:%S UTC" | |
| fi | |
| } | |
| if [ $# -eq 0 ]; then | |
| echo "Usage: $0 <timestamp_field1> [timestamp_field2] ..." | |
| exit 1 | |
| fi | |
| json_input=$(cat | jq '.') | |
| for field in "$@"; do | |
| lines=$(echo "$json_input" | grep -n "\"$field\":") | |
| while IFS=':' read -r line_number line_content; do | |
| comma="" | |
| if echo "$line_content" | grep -q ","; then | |
| comma="," | |
| fi | |
| line_content="${line_content//,/}" | |
| timestamp=$(echo "{ $line_content }" | jq -r ".\"$field\"") | |
| if [[ "$timestamp" =~ ^[0-9]+$ ]]; then | |
| readable_date=$(convert_timestamp "$timestamp") | |
| new_line="${line_content}${comma} \/\/ $readable_date" | |
| json_input=$(echo "$json_input" | sed "${line_number}s/$line_content,*/$new_line/") | |
| fi | |
| done <<< "$lines" | |
| done | |
| echo "$json_input" |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
input.json
output.json
{ "name": "formatter test!", "startTime": 1559781439, // 2019-06-06 00:37:19 UTC "endTime": 1559781450, // 2019-06-06 00:37:30 UTC "obj": { "type": "nested", "unixTs": 1559781423, // 2019-06-06 00:37:03 UTC "obj": { "type": "doubly nested", "unixTimestamp": 1559781446, "unixTs": 1559781423 // 2019-06-06 00:37:03 UTC } } }