0

I have an array in bash which consists of string messages. I need to use these messages as dictionary values in python. Something like this:

**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"
    },

When I try this, it only shows the first message value. does not go through the loop for errorMessage. I want the json output values should look like below for errorMessage:

"Details": {
    "LogFile": "/home/output.log",
    "Message 1": "testing the message",
    "Message 2": "this is msg2",
    "ReportFile": "/home/out.rpt"
},
5
  • It's unclear to me how you are reading this bash array into python. Commented May 25, 2018 at 15:43
  • 4
    What does this have to do with Python? Where's your Python code? Commented May 25, 2018 at 15:43
  • Did you mean like a python dictionary? Commented May 25, 2018 at 15:45
  • 2
    nod -- if what the OP really wants is an associative array, that's a very different question. Commented May 25, 2018 at 15:50
  • Welcome to the site! Check out the tour and the how-to-ask page for more about asking questions that will attract quality answers. You can edit your question to include more information, e.g., clarification about whether you are using Python. Commented May 25, 2018 at 15:54

1 Answer 1

1

Serializing A Bash Array Without Indices, Loading To A Python Array

The safe way to export a bash array for use by any other language is as a NUL-delimited stream. That is, for a regular array where you don't need the indices:

printf '%s\0' "${errorMessage[@]}" >messageList

...and then in Python...

errorMessages = open('messageList', 'r').read().split('\0')[:-1]

Serializing A Bash Array With Indices, Loading To A Python Dict

If you do need the indices, then it changes a bit:

for idx in "${!errorMessage[@]}"; do
  printf '%s\0' "$idx" "${errorMessage[$idx]}"
done >messageDict

...and on the Python side (built as proof-of-concept, not for performance):

pieces = open('messageDict', 'r').read().split('\0')
result = {}
while len(pieces) >= 2:
    k = pieces.pop(0); v = pieces.pop(0);
    result[k] = v

Building A Bash Associative Array From A Bash Numerically-Indexed Array

If by "as" a Python dictionary you mean "like" a Python dictionary, this is what an associative array is for. You can assign to one with arrayName["key"]="value"; to convert a list in the form described might look as follows:

declare -a errorMessage=( "Message1" "Message2" )
declare -A dict4=( )

for idx in "${!errorMessage[@]}"; do
  dict4["Message $((idx + 1))"]="${errorMessage[$idx]}"
done
Sign up to request clarification or add additional context in comments.

5 Comments

I tried with below code, but it prints only Message 1. It doesn't go through the loop to show Message 2. for idx in "${!errorMessage[@]}": dict4["Message $((idx + 1))"]="${errorMessage[$idx]}"; I want the output to show all error messages like below: "Details": { "LogFile": "/home/output.log", "Message 1": "testing the message", "Message 2": "this is msg2", "ReportFile": "/home/out.rpt" },
That code isn't even syntactically valid. Please don't try to squeeze multi-line reproducers into a comment box.
@Amol, ...anyhow, the code you gave above doesn't print anything at all -- it's not supposed to; it has no echo or printf commands. And the declare -A isn't optional -- if you don't include it, the string-format keys will all evaluate to index 0.
Anyhow, if your goal is to parse or generate JSON, the tools that should be used to do that from bash are completely unrelated to anything you asked in this question. See stedolan.github.io/jq
I used below code and it worked for me. errorMessage+=("$opeMsg\n") ## array with newline delimeter inside python code: errorMsgs = str("${errorMessage[@]}").splitlines() for idx in range(len(errorMsgs)): dict4["Message "+str(idx + 1)]=errorMsgs[idx];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.