Inspect nested JSON paths and rebuild a subset with gron
Flatten a JSON document with gron, select nested paths with ripgrep, and turn matching assignments back into JSON.
Updated
in short
Flatten the document, match the branch you need, and send the matching assignments to gron --ungron to rebuild a smaller JSON object.
Work through these disposable fixtures before adapting the commands to your own files. Run the steps in the same terminal session.
Tools used
Before you start
- Bash on Linux or macOS
- The listed tools installed and available on PATH
Steps
Step 1: Create a nested fixture
Two independent settings branches make the selection visible.
shtrmn_guide_dir="$(mktemp -d)" cd "$trmn_guide_dir" cat > settings.json <<'EOF' {"service":{"name":"api","limits":{"timeout":30,"retries":2}},"logging":{"level":"info"}} EOFStep 2: Inspect the available paths
--monochrome keeps the saved intermediate text free of terminal escapes.
shgron --monochrome settings.json > settings.gron cat settings.gronStep 3: Find just the limit assignments
Fixed-string matching treats the periods as ordinary path characters.
shrg --no-config -F 'json.service.limits.' settings.gronoutputjson.service.limits.retries = 2; json.service.limits.timeout = 30;
Step 4: Rebuild the selected branch
Parent objects are reconstructed from the selected assignments. Other settings are absent from the result.
shrg --no-config -F 'json.service.limits.' settings.gron | gron --ungron > limits.json cat limits.json
Further reading
[gron usage and ungron](https://github.com/tomnomnom/gron) [ripgrep fixed-string search](https://github.com/BurntSushi/ripgrep/blob/master/GUIDE.md)
FAQ
- Is this a lossless edit of the original file?
- No. The example creates a subset and leaves the source alone. Formatting and key ordering may change when JSON is rebuilt.
- Can I select by a value instead?
- Yes, but a value may appear at several paths. Inspect every matched assignment before treating the output as a configuration fragment.