简体   繁体   中英

How to get JSON data value in to separate variable using shell script

I am getting response from the below command in JSON format in .sh file (using shell script):

 **curl https://api.flipkart.net/sellers/skus/$col1/listings -H "Content-Type: application/json" -H "Authorization: Bearer $value"** 

Here is the response I am getting:

{"listingId":"LSMSW","skuId":"M7489","fsn":"ACCCQD","attributeValues":{"actual_stock_count":"1","mrp":"199","seller_listing_state":"current","procurement_sla":"2","zonal_shipping_charge":"0","stock_count":"10","local_shipping_charge":"0","listing_status":"ACTIVE","max_order_quantity_allowed":"3","fulfilled_by":"seller","fk_release_date":"2016-08-29 10:00:08","selling_price":"529","inventory_count":"10","national_shipping_charge":"0","sku_id":"M7489"},"listingValidations":null}

Now I want to extract all the value in a separate variable for reuse it like:

LISTINGID= 'listing id value'

SKUID= 'skuId value'

and many more.

If anyone know the answer please comment with explanation .

Here is a solution using jq . If data.json contains the sample data then the following bash script

#!/bin/bash
jq -M -r '
      .listingId
    , .skuId
    , .attributeValues.mrp
' data.json | \
while read -r listingId
      read -r skuId
      read -r mrp; do
   echo "$listingId $skuId $mrp"
done

produces

LSMSW M7489 199

The jq command in the script writes out the specified attributes on separate lines which are read into bash variables by the successive read -r commands. It should be clear how to extend or modify this to meet your requirements – the primary constraint is that for each line written by jq there should be a corresponding read -r .

I am not aware of any bash json parsers. I would go with Python or Php and parse the Json string in one of these languages and export values from there. In Php there is the putenv() method.

Good luck!

Edit: Check here Parsing JSON with Unix tools

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM