Skip to content

Instantly share code, notes, and snippets.

@sudocurse
Forked from fernandoacorreia/jsonpaths
Last active April 29, 2020 10:30
Show Gist options
  • Save sudocurse/baac2fe9afebfc4a0488ccc2bcc680a4 to your computer and use it in GitHub Desktop.
Save sudocurse/baac2fe9afebfc4a0488ccc2bcc680a4 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Outputs JSON paths.
#
# Based on https://news.ycombinator.com/item?id=20264654
#
# Usage:
# curl -s https://raw.githubusercontent.com/sitepoint-editors/json-examples/master/src/db.json | ./jsonpaths
jq -r --stream '
select(length > 1)
| (
.[0] | map(
if type == "number"
then "[" + tostring + "]"
else "." + "\"" + . + "\""
end
) | add
) + " = " + (.[1] | @json)
' < "${1:-/dev/stdin}"
#!/bin/bash
#
# Converts flat json such as:
#
# .clients[0].id = "59761c23b30d971669fb42ff"
# .clients[0].isActive = true
# .clients[0].age = 36
#
# back to json.
# The newline in the middle of the sed command is for BSD compatibility
#
# Still one problem:
# - top-level arrays flatten to "[0].asdf" which cause invalid path expressions
# The only hack I can think of right now for this is to wrap top level arrays
# as a value in a pair in the top level object:
# sed -E 's/(^\[[0-9]\])/.TLA\1/g'
# along with the <<< '{"TLA":[]}' listed below instead of <<< '{}'
#
# Doing so would produce the following:
# % echo '["g", 3, "throw"]' | catj | sed -E 's/(^\[[0-9]\])/.TLA\1/g' | uncatj
# {
# "TLA": [
# "g",
# 3,
# "throw"
# ]
# }
# This ugly change also forces an extra element into normal objects:
#
# % echo '.HostConfig.PortBindings.HostIp = ""' | uncatj
# {
# "TLA": [],
# "HostConfig": {
# "PortBindings": {
# "HostIp": ""
# }
# }
# }
# I hate it but it works
( jq -r "$(sed -E 's/(^\[[0-9]\])/.TLA\1/g ; s/$/ |/;$a\
.')" <<< '{"TLA":[]}' ) < "${1:-/dev/stdin}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment