Home > Enterprise >  shell script: Returning wrong output
shell script: Returning wrong output

Time:04-07

In the given script, the nested key is not getting appended with the value. Could not figure out where the script going wrong. Please help me here

#!/bin/bash

echo "Add the figma json file path"
read path

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

echo $(cat $figma_json | jq -r '.color | to_entries[] | "\(.key):\(.value| if .value == null then .[] | .value  else .value end)"')

Sample Input

{
  "color": {
    "white": {
      "description": "this is just plain white color",
      "type": "color",
      "value": "#ffffffff",
      "extensions": {
        "org.lukasoppermann.figmaDesignTokens": {
          "styleId": "S:40940df38088633aa746892469dd674de8b147eb,",
          "exportKey": "color"
        }
      }
    },
    "gray": {
      "50": {
        "description": "",
        "type": "color",
        "value": "#fafafaff",
        "extensions": {
          "org.lukasoppermann.figmaDesignTokens": {
            "styleId": "S:748a0078c39ca645fbcb4b2a5585e5b0d84e5fd7,",
            "exportKey": "color"
          }
        }
      }
    }
  }
}

Actual output:

white:#ffffffff gray:#fafafaff 

Excepted Output:

white:#ffffffff gray:50:#fafafaff

Please find the input file link

CodePudding user response:

Here's a solution using tostream instead of to_entries to facilitate simultaneous access to the full path and its value:

jq -r '
  .color | tostream | select(.[0][-1] == "value" and has(1)) | .[0][:-1] .[1:] | join(":")
' "$figma_json"
white:#ffffffff
gray:50:#fafafaff

Demo

CodePudding user response:

An approach attempting to demonstrate bash best-practices:

#!/bin/bash

figma_json=$1                              # prefer command-line arguments to prompts
[[ $figma_json ]] || {
  read -r -p 'Figma JSON file path: ' path # read -r means backslashes not munged
  figma_json=${path//[[:space:]]/}         # parameter expansion is more efficient than tr
}

jq -r '
  def recurse_for_value($prefix):
    to_entries[]
    | .key as $current_key
    | .value?.value? as $immediate_value
    | if $immediate_value == null then
        .value | recurse_for_value(
                   if $prefix != "" then
                     $prefix   ":"   $current_key
                   else
                     $current_key
                   end
                 )
      else
        if $prefix == "" then
          "\($current_key):\($immediate_value)"
        else
          "\($prefix):\($current_key):\($immediate_value)"
        end
      end
    ;
  .color |
  recurse_for_value("")
' "$figma_json"
  • Related