Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get all nested keys and values using jq

I have a json like this

{
  "outer1": {
    "outer2": {
      "outer3": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    "outer4": {
      "key1": "value1",
      "key2": "value2"
    }
  }
}

I want output to be

[outer1.outer2.outer3]
key1 = value1
key2 = value2

[outer1.outer2.outer4]
key1 = value1
key2 = value2

I tried jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]' test.json But its not what is what I want exactly

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assuming your input looks like this:

{
  "outer1": {
    "outer2": {
      "outer3": {
        "key1": "value1",
        "key2": "value2"
      },
      "outer4": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  }
}

You could use the --stream option to read the input as a stream of path-value pairs. For instance:

jq --stream -n '
  reduce (inputs | select(has(1))) as [$path, $val] ({};
    .[$path[:-1] | join(".")][$path[-1]] = $val
  )
'
{
  "outer1.outer2.outer3": {
    "key1": "value1",
    "key2": "value2"
  },
  "outer1.outer2.outer4": {
    "key1": "value1",
    "key2": "value2"
  }
}

Next, format this JSON according to your needs. For example using to_entries for both levels:

jq --stream -nr '
  reduce (inputs | select(has(1))) as [$path, $val] ({};
    .[$path[:-1] | join(".")][$path[-1]] = $val
  )
  | to_entries[] | "[\(.key)]", (
      .value | to_entries[] | "\(.key) = \(.value)"
    ), ""
'
[outer1.outer2.outer3]
key1 = value1
key2 = value2

[outer1.outer2.outer4]
key1 = value1
key2 = value2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading