Skip to content

Instantly share code, notes, and snippets.

@mcwalrus
Created October 16, 2024 02:03
Show Gist options
  • Select an option

  • Save mcwalrus/f5b31a66d55a9895d49a430f60c1254f to your computer and use it in GitHub Desktop.

Select an option

Save mcwalrus/f5b31a66d55a9895d49a430f60c1254f to your computer and use it in GitHub Desktop.
json unix formatter
#!/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"
@mcwalrus
Copy link
Author

Example

$ ./json-unix-formatter.sh unixTs startTime endTime < input.json > output.json

input.json

    "name": "formatter test!",
    "startTime": 1559781439,
    "endTime": 1559781450,
    "obj": {
        "type": "nested",
        "unixTs": 1559781423,
        "obj": {
            "type": "doubly nested",
            "unixTimestamp": 1559781446,
            "unixTs": 1559781423
        }
    }
}

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
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment