4

EDIT: As pointed out by some users, the request does not actually returns a JSON, but a string encoded JSON. The issue here is not actually parsing the JSON in python, but writing it in such a way that a request can be sent to the API. Therefore, it's not necessary to use the json python library.

I'm using the various google APIs (slides, drive, sheets and such) with a python program. I am having issues accessing the properties in the JSON that the API requests return.

Take a slides presentations().get request for example. It returns an instance of presentation. And I want to access its Slides property, which is an array of page objects.

So I am trying the code

slideInfo = SLIDES.presentations().get(presentationId=presId).execute()
slideInfo = slideInfo.get(['slides'][0]['pageType'])

But I get an error message saying "TypeError: string indices must be integers"

However, I thought that using brackets with a string was an acceptable replacement for accesing with a dot. In fact, I don't know how to translate this to dot accesors because it throws a syntax error since the keys have to be wrapped in quotes.

'slides'[0].'pageType' 

throws syntax error because of the dot, and without the dot it doesnt work either

3 Answers3

5

So with the JSON representation in the docs:

{
  "presentationId": string,
  "pageSize": {
    object (Size)
  },
  "slides": [
    {
      object (Page)
    }
  ],
  "title": string,
  "masters": [
    {
      object (Page)
    }
  ],
  "layouts": [
    {
      object (Page)
    }
  ],
  "locale": string,
  "revisionId": string,
  "notesMaster": {
    object (Page)
  }
}

You can access the slides using: slideInfo.get('slides') or slideInfo['slides']

So if you want to get the pageType of the first slide, it would be:

slideInfo['slides'][0]['pageType']

or

slideInfo.get('slides')[0].get('pageType')
Ryan
  • 2,167
  • 2
  • 28
  • 33
0

I think you're actually getting a string back. JSON objects act exactly like dictionaries, by the way. You should use the json package to parse your result first. If you are actually getting a proper JSON result, you should access it like a dictionary

import json

slideInfo = SLIDES.presentations().get(presentationId=presId).execute()

# parse the JSON object into a dict
slideInfo = json.parse(slideInfo)
# access the JSON object like a dict
slideInfo = slideInfo['slides'][0]['pageType']
M Z
  • 4,571
  • 2
  • 13
  • 27
0

It looks like the request is returning a json encoded string. In that case, you have to load that into a dictionary using python's standard json library.

import json

slideInfo = SLIDES.presentations().get(presentationId=presId).execute()
slideInfo = json.loads(slideInfo)
slideInfo = slideInfo.get('slides')[0]['pageType']
lucianopaz
  • 1,212
  • 10
  • 17