R
R
ramazan2015-07-10 20:37:43
Python
ramazan, 2015-07-10 20:37:43

Why does an error occur when a variable that does not change is removed from the loop?

python 2.7
Why does it work like this:

import urllib, json

url_members = 'https://api.vk.com/method/groups.getMembers?group_id=67824212'
for j in range(3):
    response_url_members = urllib.urlopen(url_members)
    members = json.loads(response_url_members.read())['response']['users'][j]
    print(members)

And if you remove the response_url_members variable from the error loop:
import urllib, json

url_members = 'https://api.vk.com/method/groups.getMembers?group_id=67824212'
response_url_members = urllib.urlopen(url_members)
for j in range(3):
    members = json.loads(response_url_members.read())['response']['users'][j]
    print(members)

Traceback (most recent call last):
  File "/home/eq/PycharmProjects/vk_stat_users/main.py", line 30, in <module>
    members = json.loads(response_url_members.read())['response']['users'][j]
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

The first option is not suitable - slow. What can be done?
upd: print in both variants added to the loop

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Klimenko, 2015-07-10
@voiceofnoise

import urllib, json

url_members = 'https://api.vk.com/method/groups.getMembers?group_id=67824212'
response_url_members = urllib.urlopen(url_members)
data = json.loads(response_url_members.read())
members = data['response']['users']
print(members)

in the first option, the URL is requested three times;
in the second, the URL is requested once, the first read call takes all the data, and the second one will already drop an empty string that is not valid json, hence the error.
At the same time, at each iteration of the loop, the conversion of the same data to json is called.
besides this, the loop itself is generally useless, since a value will be written to the members variable at each iteration and overwritten by the next one, it will be easier to refer to the index immediately. members = data['response']['users'][2]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question