My function returns a string value which I have assigned to variables. I am converting it to json and I want to return the value of 'printer_id'
函数返回赋给变量的字符串值。我将它转换为json我想返回'printer_id'的值
Code :
代码:
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]
Added the curly braces , Test runs successfully now , Output:=========================== 1 passed in 0.01 seconds =========================== Process finished with exit code 0
添加了花括号,现在测试运行成功,输出:= = = = = = = = = = = = = = = = = = = = = = = = = = = 1通过0.01秒= = = = = = = = = = = = = = = = = = = = = = = = = = =过程完成退出代码0
1 个解决方案
#1
0
The decoded json will be a dictionary, you can reference its keys directly:
解码后的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']
#1
0
The decoded json will be a dictionary, you can reference its keys directly:
解码后的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']