0

I'm trying to write a script to get a list of all the keys of an object from a file in linux terminal.

The file contains something like this:

{
    "general" : {
       "street" : "Av. Roadmin",
       "name" : "Batman",
       "phone" : "125478",
       "pets": {
                   "dog":"Hurry",
                   "cat": "Aria"
               }
       }
}    

And I want the next output:

general.street
general.name
general.phone
general.pets.dog
general.pets.car

Somebody can help me, please?

Thanks!

hek2mgl
  • 152,036
  • 28
  • 249
  • 266

1 Answers1

3

You can use jq, like this:

jq -r 'paths(scalars)|join(".")' file.json

From: https://github.com/stedolan/jq/issues/78#issuecomment-348818517

If you want to print the keys along with their values:

jq -r 'paths(scalars) as $p|"\($p|join(".")): \(getpath($p))"' file.json 
general.street: Av. Roadmin
general.name: Batman
general.phone: 125478
general.pets.dog: Hurry
general.pets.cat: Aria
hek2mgl
  • 152,036
  • 28
  • 249
  • 266