Home > Blockchain >  How to iterate and parse JSON Array dynamically using shell script
How to iterate and parse JSON Array dynamically using shell script

Time:09-16

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.

CodePudding user response:

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
  • Related