Моята функция връща стойност, която съм задал на променливи. Преобразувам го в 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]
Добавени са фигурни скоби, сега тестът се изпълнява успешно, Output: =========================== 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"]