Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to parse JSON strings with argparse when executing the script with bash?

I want to parse a JSON string given as an argument to the argparse module of a python script. The contents of the JSON string are defined in a bash file, which calls the python script. How should I escape the JSON string, so that it is properly parsed? So far, executing the bash script throws an unrecognized arguments error.

The bash file defines the CONTENT variable and executes the python script.

CONTENT='"{\"argument\": 5}"'
python script.py --content $CONTENT

The python script uses the argparse module to parse the string, but throws an error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import json
import argparse


parser = argparse.ArgumentParser()
parser.add_argument("--content", type=str)
args = parser.parse_args()

content = json.loads(args.content)
print(f"Content: {content}")

>Solution :

Just correct the quoting in the shell script:

CONTENT='{"argument": 5}' 
python script.py --content "$CONTENT"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading