我正在撰寫一個 bash 腳本,它讀取 JSON 字串,然后根據 JSON 值回圈以執行 CLI 命令。
#!/usr/bin/env bash
jq --version > /dev/null 2>&1 || { echo >&2 "jq is required but it's not installed. Aborting."; exit 1; }
read -r -d '' USER_ACTIONS << EOM
{
"user1": [
"action1"
],
"user2": [
"action2",
"action3"
]
}
EOM
USERS= #TODO
for user in USERS; do
ACTIONS= #TODO
for action in ACTIONS; do
echo "Executing ${command} ${user}-${action}"
done
done
如果 jq 存在于服務器中,我如何填充 USERS 和 ACTIONS 變數?
uj5u.com熱心網友回復:
用香草玩似乎更好js( nodejs):
const myvar={
"user1": [
"action1"
],
"user2": [
"action2",
"action3"
]
};
for (let user in myvar) {
myvar[user].forEach((action) => {
console.log("Executing command " user "-" action);
});
}
輸出
Executing command user1-action1
Executing command user2-action2
Executing command user2-action3
用法
node script.js
與 bash 一起使用
您可以洗掉執行字串,然后:
node script.js | bash
uj5u.com熱心網友回復:
根據您要執行的命令,如果可以從 jq 中執行,則將回圈也移動到內部會更容易。有幾種方法可以做到這一點。以下是一些示例,都產生相同的輸出:
jq -r 'to_entries[] | "Executing command \(.key)-\(.value[])"' <<< "$USER_ACTIONS"
jq -r 'keys[] as $user | "Executing command \($user)-\(.[$user][])"' <<< "$USER_ACTIONS"
jq -r --stream '"Executing command \(.[0][0])-\(.[1]? // empty)"' <<< "$USER_ACTIONS"
輸出:
Executing command user1-action1
Executing command user2-action2
Executing command user2-action3
uj5u.com熱心網友回復:
請您嘗試以下方法:
#!/bin/bash
declare -a users # array of users
declare -A actions # array of actions indexed by user
read -r -d '' user_actions << EOM
{
"user1": [
"action1"
],
"user2": [
"action2",
"action3"
]
}
EOM
while IFS=$'\t' read -r key val; do
users =( "$key" ) # add the user to the array "users"
actions[$key]="$val" # associate the actions with the user
done < <(jq -r 'to_entries[] | [.key, .value[]] | @tsv' <<< "$user_actions")
for user in "${users[@]}"; do # loop over "users"
IFS=$'\t' read -r -a vals <<< "${actions[$user]}"
for action in "${vals[@]}"; do
echo yourcommand "$user" "$action"
done
done
輸出:
yourcommand user1 action1
yourcommand user2 action2
yourcommand user2 action3
[說明]
- 該
jq命令輸出 TSV,如下所示:
user1\taction1
user2\taction2\taction3
其中\t表示用作欄位分隔符的制表符。
- 第一個
read內置命令分配key給第一個欄位和val其余欄位。如果val包含兩個或更多欄位,它將在下read一個回圈中使用 tne next 內置分割。 - 如果輸出看起來不錯,則洗掉
echo該字串并將其替換yourcommand為命令名稱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/519938.html
標籤:json重击jq
上一篇:地震資料分組問題
