0

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.

Rodia
  • 1,407
  • 8
  • 22
  • 29
Urvashi
  • 239
  • 2
  • 10
  • Given the JSON has at least one node `attributeValues` which contains other data which would present a number of issues when parsing with a shell script, is it not acceptable to use a scripting language such as Python and then export the results as environment variables? – glennstar Sep 08 '16 at 07:27
  • I am using shell script. then how can i parse json response./ – Urvashi Sep 08 '16 at 07:39
  • No.I used this but it shows Failed writing body – Urvashi Sep 08 '16 at 07:54
  • Use `jq` (json query), it can handle parsing a json stream. – David C. Rankin Sep 08 '16 at 20:51

2 Answers2

0

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.

jq170727
  • 13,159
  • 3
  • 46
  • 56
-1

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

Community
  • 1
  • 1
Maciej
  • 161
  • 1
  • 1
  • 7
  • `jq` is a popular and powerful cli tool for parsing JSON. PHP is not usually a good choice for scripting as there are so many versions and settings which may influence the behaviour of the PHP script. If the shell script is going to be large in complexity then consider a language like Python – Sam Anthony May 08 '19 at 05:31