当前位置: 动力学知识库 > 问答 > 编程问答 >

python - String indexes must be integers?

问题描述:

Hey I am having problems accessing some lists.

I can access Items using this code:

 data = session.get(BASE_URL + 'tori_market.php',params={'format': 'json'}).json()

except ValueError:

for item in data['items']:

print(item['price'])

But I can not access User using the same code:

data = session.get(BASE_URL + 'tori_market.php',params={'format': 'json'}).json()

except ValueError:

for users in data['user']:

print(user['max'])

Edit: I've posted the wrong code,here is the one i'm using.

data = session.get(BASE_URL + 'tori_market.php',params={'format': 'json'}).json()

except ValueError:

for users in data['user']:

print(users['balance'])

What is wrong with it?

You can check how the API directory are build in this link.

The full traceback is:

 Traceback (most recent call last):

File "/Users/Cristi/Desktop/RealBot/prova.py", line 34, in <module>

data = session.get(BASE_URL + 'tori_market.php',params={'format': 'json'}).json()

File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/requests/models.py", line 799, in json

return json.loads(self.text, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/__init__.py", line 318, in loads

return _default_decoder.decode(s)

File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/decoder.py", line 343, in decode

obj, end = self.raw_decode(s, idx=_w(s, 0).end())

File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/decoder.py", line 361, in raw_decode

raise ValueError(errmsg("Expecting value", s, err.value)) from None

ValueError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "/Users/Cristi/Desktop/RealBot/prova.py", line 37, in <module>

print(users['balance'])

TypeError: string indices must be integers

As soon as it's a passworded page i can give you a screenshot,here.

网友答案:

Edited answer

the user in above is a key in json data, so when you do

for users in data["user"]

you are already iterating over its keys.

Instead, for sake of brevity, do,

for key in data["user"]:
    print key, data["user"][key]

This will print all the data within the user dict for you. So now key can take the values of "balance" etc.


Original answer

This is a typo between users and user, you use:

for users in data['user']:

but access it as:

print(user['max'])

Instead access it as:

print(users['max'])
分享给朋友:
您可能感兴趣的文章:
随机阅读: