Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find something in a json file using Bash

Tags:

json

jq

I would like to search a JSON file for some key or value, and have it print where it was found.

For example, when using jq to print out my Firefox' extensions.json, I get something like this (using "..." here to skip long parts) :

{
  "schemaVersion": 31,
  "addons": [
    {
      "id": "[email protected]",
      "syncGUID": "{e6369308-1efc-40fd-aa5f-38da7b20df9b}",
      "version": "2.0.0",
      ...
    },
    {
      ...
    }
  ]
}

Say I would like to search for "[email protected]", and would like an output which shows me where it was found with something like this:

{ "addons": [ {"id": "[email protected]"} ] }

Is there a way to get that with jq or with some other json tool?

I also tried to simply list the various ids in that file, and hoped that I would get it with jq '.id', but that just returned null, because it apparently needs the full path.

In other words, I'm looking for a command-line json parser which I could use in a way similar to Xpath tools

like image 839
mivk Avatar asked Sep 18 '25 02:09

mivk


1 Answers

The path() function comes in handy:

$ jq -c 'path(.. | select(. == "[email protected]"))' input.json
["addons",0,"id"]

The resulting path is interpreted as "In the addons field of the initial object, the first array element's id field matches". You can use it with getpath(), setpath(), delpaths(), etc. to get or manipulate the value it describes.

like image 142
Shawn Avatar answered Sep 19 '25 23:09

Shawn