How to get keys from JSON by using jq

How to get keys from JSON by using jq

#Development#jq#Tips

Hello 2022 👋

Now, I'm optimizing my package.json for Dependabot to be automatically update and able to run GitHub Actions which are related in this issue. Before that, I should tidy up npm package.json that modules are either dependencies or devDependencies.

So, I'd like to introduce retrieving keys of JSON by using jq command.

Filtering Keys

We can use jq 'keys' command to deal with JSON displaying all keys.

$ echo '{"foo": true, "bar": 0}' | jq 'keys'
[
  "foo",
  "bar"
]

You might get only keys. We don't need array type and double-quotation.

$ echo '{"foo": true, "bar": 0}' | jq -r 'keys[]'
foo
bar

Migrating Dependencies

To sum up the dependencies concerns of package.json.

$ cat package.json|jq -r '.devDependencies | keys[]' | grep --color=none gatsby | while read in
do
 [ -n "$in" ] && npm uninstall $in && npm install $in     
done

The script works for migrating devDependencies to dependencies.

Thanks!

B!

Shintaro Kaneko

January 03, 2022