0

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'

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

3
  • Thats not a JSON Commented Feb 22, 2018 at 10:16
  • You missed the opening curly brace Commented Feb 22, 2018 at 10:17
  • Added the curly braces, and now its running Commented Feb 22, 2018 at 11:34

1 Answer 1

1

The decoded json will be a dictionary, you can reference its keys directly:

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.