Search code examples
oci-python-sdk

OCI response returns a list object with one entry


The response.data attribute seems to return a Python list type object, with just one entry. To get the response data into a Python dict object I have to strip out the list contents before using the json.loads function. Is there a more elegant way to do this?

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_contents = (myresp[0])

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

Solution

  • It seems like you are trying to retrieve data on only a single instance.

    list_instances is meant to return a list of instances, hence why the returned object is a list.

    If you are trying to retrieve data on only a single instance, I recommend using the get_instance API. Since this API is designed to return only a single instance, the returned object won't be a list, and so won't require you to index into the list to get the instance's data.