-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

5
  • 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. Commented Jun 12, 2020 at 0: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. Commented Jun 12, 2020 at 2:44
  • Does this help? stackoverflow.com/questions/11392033/… Commented Jun 12, 2020 at 2: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. Commented Jun 12, 2020 at 2:57
  • @CharlesDuffy: right said. it makes sense. Commented Jun 12, 2020 at 3:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.