通过命令提示符传递json

问题描述 投票:0回答:1

我通过命令提示符将以下json传递为

$python new.py {'scenarioId':'null','scenarioName':'EC_02','scenarioDesc':'EC_02','riskEngine':'null'}

以及当我运行以下命令时:

import sys
import json
str_json = sys.argv[1].replace("'", '"')

try:
    b = json.dumps(str_json)
    a_json = json.loads(b)
    print("Stress JSON is as follows \n",a_json)
except json.decoder.JSONDecodeError:
    print("Not a valid JSON")

d = json.dumps(str_json)
dat = json.loads(d)
print(dat['scenarioId'])

这是一个有效的json,但最后一行出现错误TypeError:字符串索引必须为整数。当我在代码本身中将其初始化为str_json时,它可以正常工作。该如何解决?

python json python-3.x command prompt
1个回答
0
投票

尝试一下:

import sys
import json
str_json = sys.argv[1].replace("'", '"')
try:
    b = json.dumps(str_json)
    a_json = json.loads(json.loads(b))
    print("Stress JSON is as follows \n",a_json)
except json.decoder.JSONDecodeError:
    print("Not a valid JSON")


print(a_json['scenarioId'])

输出:

Stress JSON is as follows 
 {'scenarioId': 'null', 'scenarioName': 'EC_02', 'scenarioDesc': 'EC_02', 'riskEngine': 'null'}
null
© www.soinside.com 2019 - 2024. All rights reserved.