Python Forum
TypeError: string indices must be integers - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: TypeError: string indices must be integers (/thread-10026.html)



TypeError: string indices must be integers - dsorci - May-09-2018

Hello All,

When I run the below script, I get this error...

print ('{}|{}|{}'.format(x['hostname'], x ['vlanid'], x['vlandescription']))
TypeError: string indices must be integers

...here is my script...
import sys
import requests,urllib3,json,pprint
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def get_vlanid ():
    response = raw_input("Please Enter VLAN ID:")
    url = 'https://<URL>:8443/nds/vlanDB/vlantool/vlanid/'
    body = '[{"vlanid": "%s"}]' % response
    s = requests.session()
    req = s.post(url, headers={'apikey': '<API_KEY>','Accept': 'application/json', 'Content-type': 'application/json'}, verify=False, data=body)
    result = json.loads(req.content)
    for x in result:
        print ('{}|{}|{}'.format(x['hostname'], x ['vlanid'], x['vlandescription']))

#get_all()
get_vlanid ()
I think on the json I'm pulling from is identifying the vlanid, as an integer? And, I need to tell the print command to expect such?

Any advice?


RE: TypeError: string indices must be integers - snippsat - May-09-2018

When you loop over result you get dictionary key string back.
result is just a Python dictionary,that json.load() make.
There also no need to use json.load() as Requests has this build in.
Make your error and fix.
>>> import requests
>>> 
>>> r = requests.get('https://api.github.com/feeds')
>>> data = r.json()
>>> data
{'_links': {'timeline': {'href': 'https://github.com/timeline',
                         'type': 'application/atom+xml'},
            'user': {'href': 'https://github.com/{user}',
                     'type': 'application/atom+xml'}},
 'timeline_url': 'https://github.com/timeline',
 'user_url': 'https://github.com/{user}'}
>>> 
>>> for x in data:
...     x['timeline_url']
...     
Traceback (most recent call last):
  File "<string>", line 428, in runcode
  File "<interactive input>", line 2, in <module>
TypeError: string indices must be integers

>>> # x is just key strings 
>>> # To get timeline_url
>>> data['timeline_url']
'https://github.com/timeline'
>>>