1

I'm trying to parse and iterate below JSON Array using shell script with jq. I want to get the product.productID, product.productName, product.details.info and product.details.desc.

And assign these value dynamically in below input variable

input='{"pid"':$productID', "pname"':$productName', "pd": { "info"':$info', "desc":':$desc'}}'

Same I want to do for inventory JSON array also.

product.json

{
  "product": [
    {
      "productID": "PR12343",
      "productName": "iphone13",
      "price": 1000,
      "details": {
        "info": "test info",
        "desc": "test desciption"
      }
    },
    {
      "productID": "PR8493",
      "productName": "iphone14",
      "price": 1200,
      "details": {
        "info": "test info",
        "desc": "test desciption"
      }
    }
  ],
  "inventory": [
    {
      "id": "INV8393",
      "configuration": "local",
      "name": "Macbook"
    },
    {
      "id": "INV8322",
      "configuration": "local",
      "name": "iPad"
    }
  ]
}

product.sh

#!/bin/bash
#
inputFile=product.json
request=$(jq -c . $inputFile)
#echo "$request" | jq -r '.product[]|"\(.productID) , \(.productName)"'

jq -c '.[]' product.json | while read i; do
    # do stuff with $i
    echo $i
    input='{"pid"':$productID', "pname"':$productName', "pd": { "info"':$info', "desc":':$desc'}}'
    # make rest api call
done

Can someone please help how can I iterate and parse the value in shell script. Appreciated your help in advance.

1
  • What's the point of input='...'? If you want to transform your input JSON into other JSON, make jq do that; don't do it in bash. Commented Sep 15, 2022 at 20:16

1 Answer 1

2

This will give you the product info, one per line:

jq -c '.product[] | {pid: .productID, pname: .productName, pd: .details}' product.json
{"pid":"PR12343","pname":"iphone13","pd":{"info":"test info","desc":"test desciption"}}
{"pid":"PR8493","pname":"iphone14","pd":{"info":"test info","desc":"test desciption"}}

So you could read it in a loop:

jq -c '.product[] | {pid: .productID, pname: .productName, pd: .details}' product.json \
| while IFS= read -r input; do
    # do something with "$input"
done

Or capture the output into an array and iterate over that

mapfile -t inputs < <(jq -c ...)
for input in "${inputs[@]}"; do
    # do something with "$input"
done
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.