Home > Software design >  Shell Script error: "For loop" is not throwing the expected output
Shell Script error: "For loop" is not throwing the expected output

Time:04-06

I have json file which extract the color value from the file. For some reason, it only fetch only one block of code & for the rest it throws error.

snippet

#!/bin/bash

clear

echo "Add the figma json file path"
read path

figma_json="$(echo -e "${path}" | tr -d '[:space:]')"

echo "*****************************************"


color_values=$(cat $figma_json | jq -r '.color')
color_keys=$(cat $figma_json | jq -r '.color | keys' |sed 's,^ *,,; s, *$,,'| tr -s ' ' | tr ' ' '_')

echo $color_keys


for c_key in $color_keys
do

    echo "key string: $c_key"

    echo $color_values | jq ".$c_key.value"
    echo "*********************************************"

done

Output

trimmed string: "gray1",
{
  "description": "",
  "type": "color",
  "value": "#333333ff",
  "extensions": {
    "org.lukasoppermann.figmaDesignTokens": {
      "styleId": "S:0b49d19e868ec919fac01ec377bb989174094d7e,",
      "exportKey": "color"
    }
  }
}
null
*********************************************
trimmed string: "gray2" //Expected output
"#333333ff"
*********************************************

If we look at the second output it prints the hex value of gray2 which is the expected output Please use the follow link to get the json file link

CodePudding user response:

It's quite unclear what you are aiming at, but here's one way how you would read from a JSON file using just one call to jq, and most probably without the need to employ sed or tr. The selection as well as the formatting can easily be adjusted to your liking.

jq -r '.color | to_entries[] | "\(.key): \(.value.value)"' "$figma_json"
gray1: #333333ff
gray2: #4f4f4fff
gray3: #828282ff
gray4: #bdbdbdff
gray5: #e0e0e0ff
gray6: #f2f2f2ff
red: #eb5757ff
orange: #f2994aff
yellow: #f2c94cff
green1: #219653ff
green2: #27ae60ff
green3: #6fcf97ff
blue1: #2f80edff
blue2: #2d9cdbff
blue3: #56ccf2ff
purple1: #9b51e0ff
purple2: #bb6bd9ff

Demo

  • Related