-2

I wanted to use python return /sys.exit value as variable for further processing.

#!/bin/bash
cat myjson.json | \
output=($(python -c 'import json,sys;obj=json.load(sys.stdin);
                     result =[];
                         for y in [x["_source"]["memberId"] for x in obj["hits"]["hits"]]:
                             result+=[y];
                      sys.exit(result)'))
echo 'output'$output

what is the best approach to read JSON data in the shell script using Python and store the Python output in an array variable of shell script

Prabeeth
  • 3
  • 3
  • 1
    `sys.exit()` can only return integer values. If you want json, that will have to be printed as regular output. Or written to a file, saved to a database, etc. – John Gordon Jun 12 '20 at 00:52
  • On a side note, depending on your requirement, you may consider using powerful Linux tools such as grep, awk, sed. Believe it or not, these tools are way faster and works flawlessly on a shell. – ravi Jun 12 '20 at 02:44
  • Does this help? https://stackoverflow.com/questions/11392033/passing-python-array-to-bash-script-and-passing-bash-variable-to-python-functio – Hoppo Jun 12 '20 at 02:45
  • @RaviJoshi, structure-unaware tools should absolutely not be used to parse structured languages like JSON or XML; those are why we have specialty tools like `jq` or `xmlstarlet` specializing in their handling while being intentionally easy to use from scripts. – Charles Duffy Jun 12 '20 at 02:57
  • @CharlesDuffy: right said. it makes sense. – ravi Jun 12 '20 at 03:00

1 Answers1

1

The text captured in output is the stuff printed by the Python command to standard output. sys.exit only sets the exit code of the command, which can be captured as $? before running another command.

l0b0
  • 55,365
  • 30
  • 138
  • 223