我通过命令提示符将以下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时,它可以正常工作。该如何解决?
尝试一下:
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