0

i am trying to loop through a simple json file (see link) and to calculate the sum of all integers from the file.

When iterating through the file I receive the following error: TypeError: string indices must be integers

Could you please help.

code below

import urllib.request, urllib.parse, urllib.error
import json
total=0
#url = input('Enter URL: ')
url= ' http://py4e-data.dr-chuck.net/comments_42.json'
uh=urllib.request.urlopen(url)
data = uh.read().decode()
print('Retrieved', len(data), 'characters')
print(data)

info = json.loads(data)
print('User count:', len(info)) #it displays "User count: 2" why?

for item in info:
    num=item["comments"][0]["count"]
    total=total+num
print (total)
2
  • 1
    I was able to extract the link you are mentioning from your code, but it is better to post a shortened (but representative) version the json file as text, possibly with a link to the full file. That's probably the reason that someone has downvoted your question. Commented Jul 8, 2020 at 9:59
  • To answer your question in the code, it displays 2 because the dictionary at the top level in your json file has two items: "notes" and "comments". Commented Jul 8, 2020 at 10:01

1 Answer 1

1

The json file starts with a note. Your for-loop reads the keys of a dictionary, so the first item is 'note' (a string), which can only be subscripted with an integer, hence the error message.

You probably want to loop over info["comments"] which is the list with all dictionaries containing 'name' and 'count':

for item in info["comments"]:
    num=item["count"]
    total=total+num
print (total)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.