jq:将嵌套对象添加到 JSON

api*_*nes 2 bash json jq

我有一个包含多个配置文件的 json 文件:

{
  "profile1": {
    "user": "user1",
    "channel": "channel1",
    "hook": "hook1"
  },
  "default": {
    "user": "user1",
    "channel": "channel1",
    "hook": "hook2"
  }
}
Run Code Online (Sandbox Code Playgroud)

我想使用 jq 插入另一个配置文件“test”,这样最终结果将是

{
  "profile1": {
    "user": "user1",
    "channel": "channel1",
    "hook": "hook1"
  },
  "default": {
    "user": "user1",
    "channel": "channel1",
    "hook": "hook2"
  },
  "test": {
    "user": "user3",
    "channel": "channel3",
    "hook": "hook3"
  }
}
Run Code Online (Sandbox Code Playgroud)

我可以直接在命令行中执行以下操作:

cat filename | 
    jq  '.+  { "test": { "user": "u3", "channel" : "c3", "hook": "w3" } }'
Run Code Online (Sandbox Code Playgroud)

但是当我在 bash 脚本中尝试它时:

cat "$CONF_FILE" | 
    jq --arg p "$PROFILE" --arg u "$U" --arg c "$C" --arg w "$WH" \
    '.+ { $p: { "user": $u, "channel": $c, "hook": $w } }' `
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

jq: error: syntax error, unexpected ':', expecting '}' (Unix shell quoting issues?) at <top-level>, line 1:
.+ { $p: { "user": $u, "channel": $c, "hook": $w } }
jq: error: syntax error, unexpected '}', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.+ { $p: { "user": $u, "channel": $c, "hook": $w } }
jq: 2 compile errors
Run Code Online (Sandbox Code Playgroud)

我尝试用引号将变量引起来,但随后我只得到字符串 $p:

cat "$CONF_FILE" | 
    jq --arg p "$PROFILE" --arg u "$U" --arg c "$C" --arg w "$WH" \
    '.+ { "$p": { "user": $u, "channel": $c, "hook": $w } }' 
Run Code Online (Sandbox Code Playgroud)

结果:

{
  "profile1": {
    "user": "user1",
    "channel": "channel1",
    "hook": "hook1"
  },
  "default": {
    "user": "user1",
    "channel": "channel1",
    "hook": "hook2"
  },
  "$p": {
    "user": "user3",
    "channel": "channel3",
    "hook": "hook3"
  }
}
Run Code Online (Sandbox Code Playgroud)



编辑:我找到了一个看似临时的解决方案,将对象转换为数组,编辑值(现在配置文件名称是一个值而不是键)并将数组转换回对象:

cat "$CONF_FILE" | 
    jq --arg p "$PROFILE" --arg u "$U" --arg c "$C" --arg w "$WH" \
    'to_entries | .+ [ { "key": $p, "value": { "user": $u, "channel": $c, "hook": $w } } ] | from_entries'
Run Code Online (Sandbox Code Playgroud)

这看起来很粗糙,但是很有效。我仍然希望有更好的解决方案......

小智 6

在动态键周围使用括号:

jq --arg p "$PROFILE" --arg u "$U" --arg c "$C" --arg w "$WH" \
'. + {($p): {"user": $u, "channel": $c, "hook": $w}}' "$CONF_FILE"
Run Code Online (Sandbox Code Playgroud)