简体   繁体   中英

Passing a JSON as a parameter from the run configuration in PyCharm

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.

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM