From oci response to a Python dictionary

Viewed 70

Looking to convert an oci response to a Python dict, so I can print out various fields. But I can't manage to get a Python dictionary object.

    import oci
    import json

    myresp = core_client.list_instances(compartment,display_name="myinstance").data
    # myresp is of type LIST
    # Convert the Python object response to a JSON string
    myjson = json.dumps(str(myresp))
    # myjson is of type STR
    # Convert JSON string to Python dict
    mypyth = json.loads(myjson)
    print(my_pyth['id'])
    # Script fails, mypyth is of type STR, not dict as expected```
2 Answers

Fixed this by removing the outer [] brackets from the OCI response. You then have valid JSON, which you can convert to a Python dict.

import oci
import json

myresp = core_client.list_instances(compartment,display_name="myinstance").data
# myresp is of type LIST
# Strip out contents of the list
myresp_list = (myresp[0])

# Convert JSON string to Python dict
mypyth = json.loads(str(myjson_list))
print(my_pyth['id'])
# Script succeeds, mypyth is of type DIR as expected

You can try with ast:

  ast.literal_eval(myjson)

it should return the dict you are looking for. Of course:

  import ast
Related