shell 脚本:返回错误的输出

shell script: Returning wrong output

在给定的脚本中,嵌套键没有附加值。无法弄清楚脚本哪里出错了。请帮帮我

#!/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)"')

示例输入

{
  "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"
          }
        }
      }
    }
  }
}

实际输出:

white:#ffffffff gray:#fafafaff 

异常输出:

白色:#ffffffff gray:50:#fafafaff

请查找输入文件link

这是一个使用 tostream 而不是 to_entries 的解决方案,以方便同时访问完整路径及其值:

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

Demo

一种尝试证明的方法 bash best-practices:

#!/bin/bash

figma_json=                              # 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"