Anand
Anand

Reputation: 1973

shell script: Returning wrong output

In the given script, the nested key is not getting appended with the value. I could not figure out where the script is going wrong.

#!/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

Full input file

Upvotes: 0

Views: 149

Answers (2)

pmf
pmf

Reputation: 36151

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

Upvotes: 2

Charles Duffy
Charles Duffy

Reputation: 295500

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"

Upvotes: 1

Related Questions