Skip to content

Instantly share code, notes, and snippets.

@ayosec
Last active June 21, 2019 02:47
Show Gist options
  • Save ayosec/db2173ee2e274b19f209a91990d33db7 to your computer and use it in GitHub Desktop.
Save ayosec/db2173ee2e274b19f209a91990d33db7 to your computer and use it in GitHub Desktop.
jq: flatten JSON document
paths(scalars) as $p
| [ ( [ $p[] | tostring ] | join(".") )
, ( getpath($p) | tojson )
]
| join(" = ")

Example

jq -r '
paths(scalars) as $p
  | [ ( [ $p[] | tostring ] | join(".") )
    , ( getpath($p) | tojson )
    ]
  | join(" = ")
' <<'INPUT'
{
  "a": 1,
  "b": [ "red", "green", "blue" ],
  "c": {
    "d": [
      {
        "a": 100,
        "b": 200,
        "c": "x\ny\nz"
      },
      {
        "a": 101,
        "b": 201
      }
    ]
  }
}
INPUT

Output

a = 1
b.0 = "red"
b.1 = "green"
b.2 = "blue"
c.d.0.a = 100
c.d.0.b = 200
c.d.0.c = "x\ny\nz"
c.d.1.a = 101
c.d.1.b = 201
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment