Skip to content

Instantly share code, notes, and snippets.

@thn929
Last active November 10, 2022 15:58
Show Gist options
  • Save thn929/03937bb13e58e920b5e3071fca3edf7c to your computer and use it in GitHub Desktop.
Save thn929/03937bb13e58e920b5e3071fca3edf7c to your computer and use it in GitHub Desktop.
jq tricks
#1: human-readable dates and timestamps within context
```bash
cat something.json | jq 'walk(if type == "object" then with_entries(if(.key | contains("date")) or (.key | contains("timestamp")) then {key, value: .value|.[0:10]|tonumber|todate} else . end) else . end)'
```
#2: Like above, but filters down to just the dates and timestamps, and displays the paths to each field
```bash
cat something.json | jq 'walk(if type == "object" then with_entries(if(.key | contains("date")) or (.key | contains("timestamp")) then {key, value: .value|.[0:10]|tonumber|todate} else . end) else . end)' | jq 'del(.. | .source_data?)' | jq -r 'paths(scalars) as $p | [ ( [ $p[] | tostring ] | join(".") ), ( getpath($p) | tojson )] | join(": ")' | grep 'date\|time'
```
Combines
- #1
- **[Delete objects and arrays with jq which match a key](https://stackoverflow.com/a/47371754)** (to remove the giant blocks of `.source_data`)
- **[How to print path and key values of JSON file](https://unix.stackexchange.com/a/561489)**
- grep: to filter down to just keys containing “date” or “timestamp” (I could’ve also stayed with `jq` here but I got lazy 😅)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment