Home > Software design >  Bash. How to access parameters while looping through json with jq?
Bash. How to access parameters while looping through json with jq?

Time:09-16

i have a details.json file with a lot of entries and a shops.txt file like below. I like to have a little script which compares two values and just return the matching json entries.

[
{
    "userName": "Anne",
    "email": "[email protected]",
    "company": {
        "name": "Stack GmbH",
    },
    "details": {
        "key": "EFHJKI-KJEFT-DHMNEB",
        "prod": "Car",
    },
    "store": {
        "id": "05611a7f-a679-12ad-a3u2-0745e3650a03",
        "storeName": "shop-a57ca0a3-120c-1a73-153b-fa4231cab768",
    }
},
{
    "userName": "Tom",
    "email": "[email protected]",
    "company": {
        "name": "Stack GmbH",
    },
    "details": {
        "key": "DFSGSE-FGEAR-GWRTGW",
        "prod": "Bike",
    },
    "store": null
},
]

This is the other file "shops.txt" (can be a lot more of shops inside)

shop-a57ca0a3-120c-1a73-153b-fa4231cab768

The script is looping through the shops, for every shop it loops through the json and should compare the currentShop with the store.shop from json and then echo the user and the shop. But I can not access the specific parameters inside the json. How can I do this?

#!/bin/bash
shops="shops.txt"
while IFS= read -r line
do
  currentShop="$line"

  jq -c '.[.userName, .store.storeName]' details.json | while read i; do
  if [[ $i.store.storeName == *$currentShop* ]]; then
  echo $i.userName
  echo $currentShop
  fi
  done

done < "$shops"

CodePudding user response:

First of all, you might want to 'clean' your json, remove any trailing ,'s etc.


After looping through each line in the file we just need one select() to get the matching object.

The script could look something like:

#!/bin/bash

while read shop; do
  echo "Check: $shop"
  jq -r --arg storeName "$shop" '.[] | select(.store.storeName == "\($storeName)") | "\(.userName) - \(.store.storeName)"' details.json
done < "shops.txt"

Which will produce

Check: shop-a57ca0a3-120c-1a73-153b-fa4231cab768
Anne - shop-a57ca0a3-120c-1a73-153b-fa4231cab768

I guess this could be combined into a single call, but it seems like you want to loop over each entry found


You can test this selector on this online JqPlay Demo.

CodePudding user response:

I was able to access the values with the following command:

echo $i | jq -r '.userName'
  • Related