1

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
mikey
  • 115
  • 8

1 Answers1

0

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.

Joe
  • 2,500
  • 1
  • 14
  • 12
  • 1
    Thanks, Joe. But one disadvantage of `get_instance` is that you have to supply the instance ID, rather than the more user-friendly display_name. – mikey Jun 23 '22 at 14:03
  • Yes that's correct. But even `list_instances` takes an ID -- its just the compartment's ID instead of instance's ID. So either way you have to pass an ID – Joe Jun 23 '22 at 19:01
  • Yes, I suppose so. But stuff like the compartment ID is in my `~/.oci/config` file. Easy to access from a script running on my Linux client. I hate having to type in those long ID strings. – mikey Jun 24 '22 at 14:01