2

Can someone please tell me how to pass a JSON as a script parameter from the parameters field of the run configuration?

I'm trying to pass this JSON:

{"beam":5,"max_len_a":1.2,"max_len_b":10}

tried:

'{"beam":5,"max_len_a":1.2,"max_len_b":10}'
"{"beam":5,"max_len_a":1.2,"max_len_b":10}"
\"{"beam":5,"max_len_a":1.2,"max_len_b":10}\"
"{\"beam\":5,\"max_len_a\":1.2,\"max_len_b\":10}"

All failed.

1
  • Hello, did you see the answer? Commented Feb 25, 2022 at 17:04

2 Answers 2

3

Passing the example parameter in the question is relatively straightforward. The only rule applying is that the quotes (") have to be escaped using backslashes (\"). For a more complicated example with more rules applying see Pycharm deletes quotation marks in paramenter field.

Run/Debug Configuration: Python

Configuration tab

When specifying the script parameters, follow these rules:

(...)

  • If script parameter includes double quotes, escape the double quotes with backslashes,

So the example JSON string:

{"beam":5,"max_len_a":1.2,"max_len_b":10}

should be written as:

{\"beam\":5,\"max_len_a\":1.2,\"max_len_b\":10}

You can then easily convert the parameter to a JSON object using the script

import json
import sys

your_string = sys.argv[1]
z = json.loads(your_string)

The following screenshot shows the run configurations:

enter image description here

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

Comments

2

If you are using argparse and have an argument like this:

import argparse

parser = argparse.ArgumentParser(description='Demo-Tool')    
parser.add_argument('--params', type=str, help='JSON-serialized params dict')

You need to escape the quotes using backslashes and put quotes around the JSON. The following did the trick for me in the run configurations:

--params "{\"beam\":5,\"max_len_a\":1.2,\"max_len_b\":10}"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.