bash
に配列があります文字列メッセージで構成されます。
これらのメッセージをPythonの辞書値として使用する必要があります。このようなもの:
**Array in Bash**
errorMessage+=("testing the message")
errorMessage+=("this is msg2")
**Function with Python code in Bash**
displayJsonOutput()
{
python - <<END
import json
dict1 = {}
dict1['ScriptName']="$scriptName";
dict1['CaseName']="$option"
dict4={}
dict4['LogFile']="$logFileName";
dict4['ReportFile']="$reportFileName";
for idx in "${!errorMessage[@]}":
dict4["Message $((idx + 1))"]="${errorMessage[$idx]}";
dict1["Details"]=dict4
print(json.dumps(dict1, indent=4))
END
}
Output shown:
"Details": {
"LogFile": "/home/output.log",
"Message 1": "testing the message",
"ReportFile": "/home/out.rpt"
},
これを試すと、最初のメッセージ値のみが表示されます。 errorMessageのループを通過しません。 errorMessageのjson出力値は次のようになります。
"Details": {
"LogFile": "/home/output.log",
"Message 1": "testing the message",
"Message 2": "this is msg2",
"ReportFile": "/home/out.rpt"
},
インデックスなしのBash配列のシリアル化、Python配列への読み込み
他の言語で使用するためにbash配列をエクスポートする安全な方法は、NULで区切られたストリームとしてです。つまり、インデックスを必要としない通常の配列の場合:
...そしてPythonで...
Bash配列をインデックスでシリアル化し、Pythonの辞書にロードする
もし、あんたが行う インデックスが必要な場合、少し変更されます:
...そしてPython側で(パフォーマンスのためではなく、概念実証として構築されています):
Bash数値インデックス配列からのBash連想配列の構築
Pythonの辞書を「as」で表すと、Pythonの辞書の「のように」意味する場合、これが連想配列の目的です。
arrayName["key"]="value"
で割り当てることができます ;説明されている形式のリストを変換するには、次のようになります。