Bharath Bharath - 3 months ago 7
Python Question

pass array of dictionaries to python

I have a bash script that builds a dictionary kind of structure for multiple iterations as shown below:

{ "a":"b", "c":"d", "e":"f"}
{ "a1":"b1", "c1":"d1", "e1":"f1", "g1":"h1" }


I have appended all of them to an array in shell script and they are to be fed as an input to python script and I want the above data to be parsed as list of dictionaries.

I tried some thing like this and it didn't work.

var=({ "a":"b", "c":"d", "e":"f"} { "a1":"b1", "c1":"d1", "e1":"f1", "g1":"h1" })

function plot_graph {
RESULT="$1" python - <<END
from __future__ import print_function
import pygal
import os
import sys
def main():
result = os.getenv('RESULT')
print(result)
if __name__ == "__main__":
main()
END
}
plot_graph ${var[@]}


Arguments are being split and they are not being treated as a single variable.

Out of result will be :[ {"a":"b", ]


where as I want the entire var value to be read as a string and then I can split it into multiple dictionaries.

Please help me get over this.

Answer

seems problem of plot_graph $var

The following code should work:

var="({ 'a':'b', 'c':'d', 'e':'f'} { 'a1':'b1', 'c1':'d1', 'e1':'f1', 'g1':'h1' })"

echo $var



function plot_graph {
echo $1
RESULT="$1"   python - <<END
from __future__ import print_function
import os
import sys
def main():
    result = os.getenv('RESULT')
    print(result)
if __name__ == "__main__":
    main()
END
}
plot_graph "$var"