我的函数返回一个我赋给变量的字符串值。我将它转换为json,我想返回' printer_id'
的值代码:
import json
def getprinterid():
s='''
{
"printer_config": {
"printer_id": "AQAAAAFhvL8CXQ",
"conn_config_url": "https://connectivity",
"printer_caps_url": "https://deviceconfig",
"cred_refresh_url": "https://registration"
}
,"cloud_config": {
"eprint_enabled": true,
"sips_enabled": true,
"mobile_print_enabled": true
}
}
'''
decodedinfo = json.loads(s)
for x in decodedinfo:
if x == "printer_config":
for y in decodedinfo[x]:
if y == "printer_id":
return decodedinfo[x][y]
添加花括号,Test现在成功运行,输出:=========================== 1在0.01秒内传递=== ======================== 处理以退出代码0结束
答案 0 :(得分:1)
解码后的json将是一个字典,你可以直接引用它的键:
import json
def getprinterid():
s = '''
{
"printer_config": {
"printer_id": "AQAAAAFhvL8CXQ",
"conn_config_url": "https://connectivity",
"printer_caps_url": "https://deviceconfig",
"cred_refresh_url": "https://registration"
}
,"cloud_config": {
"eprint_enabled": true,
"sips_enabled": true,
"mobile_print_enabled": true
}
}
'''
decoded = json.loads(s)
return decoded['printer_config']['printer_id']