willemdh
willemdh

Reputation: 856

How can I loop through my json with Bash

I have a json file which looks like this:

{
  "version": {
    "Generated": "@logon",
    "Value": "Unknown",
    "LastRun": "Never"
  },
  "hostname": {
    "Generated": "@logon",
    "Value": "Unknown",
    "LastRun": "Never"
  },
  "updates": {
    "Generated": "@boot",
    "Value": "Unknown",
    "LastRun": "Never"
  }
}

How can I loop through each element in the json file in Bash which has as "Generated" value "@logon"? I guess I should use jq, but I didn't manage to find the right filter.

Upvotes: 0

Views: 7284

Answers (2)

hek2mgl
hek2mgl

Reputation: 158210

You mean this?

jq -r '.[].Generated' file.json | while read -r val ; do
    do_something "${val}"
done

Upvotes: 2

peak
peak

Reputation: 116967

If you want to use bash to loop through the JSON objects satisfying the condition, consider:

while read -r val ; do
    echo "${val}"
done < <(jq -rc '.[] | select(.Generated == "@logon")' file.json)

Output:

{"Generated":"@logon","Value":"Unknown","LastRun":"Never"}
{"Generated":"@logon","Value":"Unknown","LastRun":"Never"}

The -c option is needed if this approach to looping in bash is adopted.

Of course it would be preferable to do as much processing of JSON objects within jq as possible.

If you want to loop through the top-level key-value pairs, then you will probably want to use to_entries or maybe with_entries. For example, to print the keys of objects with .Generated == "@logon":

$ jq -r 'to_entries[] | select(.value.Generated == "@logon") | .key' input.json
version
hostname

Notice - no bash loop needed!

Upvotes: 3

Related Questions