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

Time:09-11

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.

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}")

CodePudding user response:

Just correct the quoting in the shell script:

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