Shell 变量作为 json 中的附加字段

Shell variables as additional fields in json

我可以使用以下 shell 脚本将每个用户的数据检索到 m4-$u.json 文件中

#!/bin/bash

USERID=ricardo.sanchez
PASSWORD=password
PORT=2728

for u in `cat user-list.txt`;
   do echo $u; 
   curl --user $USERID:$PASSWORD http://198.98.99.12:46567/$PORT/protects/$u | jq '.' > m4-$u.json
done

一个用于 m4-daniel.json 文件几行的用户输出如下。

[
  {
    "depotFile": "//ABND/JJEB/...",
    "host": "*",
    "isgroup": "",
    "line": "16",
    "perm": "open",
    "user": "5G_USER_GROUP"
  },
  {
    "depotFile": "//LIB/...",
    "host": "*",
    "isgroup": "",
    "line": "19",
    "perm": "write",
    "user": "6G_USER_GROUP"
  },
  {
    "depotFile": "//AND/RIO/...",
    "host": "*",
    "isgroup": "",
    "line": "20",
    "perm": "write",
    "user": "AND_USER_GROUP"
  },

在 shell 脚本 运行 期间,另外 $PORT$u 变量值需要添加到每个 json 文件的输出中。

预期json输出:-

  {
    "depotFile": "//ABND/JJEB/...",
    "host": "*",
    "isgroup": "",
    "line": "16",
    "perm": "open",
    "user": "5G_USER_GROUP",
    "port": "2728",
    "userid": "daniel"
  },

为此,我们将不胜感激。

通过将 --arg 与 jq 一起使用,您可以传递参数并用作变量 (更多信息 https://stedolan.github.io/jq/manual/v1.5/#Invokingjq

通过使用 map+,您可以遍历数组并为每个关联数组添加一个新的 属性

在你的情况下:

curl --user $USERID:$PASSWORD http://198.98.99.12:46567/$PORT/protects/$u  \
   | jq --arg a_port $PORT  --arg $u  $USER 'map(.+{"userid":$a_userid}+{"port":$a_port|tonumber})'  > m4-$u.json

参见 additionmap https://stedolan.github.io/jq/manual/v1.5/#Builtinoperatorsandfunctions