简体   繁体   中英

How to show list of certain items from JSON

I've been trying to show a list of comments from a JSON file. I keep getting this error:

Traceback (most recent call last): File "JsonExtraction.py", line 7, in for comment in len(data): TypeError: 'int' object is not iterable

My code looks like this:

import json

data = []
for line in open('rating_company_small.json', 'r'):
    data.append(json.loads(line))

for comment in len(data):
    print(comment['comment'])

Can someone explain the error?

You should iterate over data , which is a list of objects, and not over len(data) which is a number and is not iterable!

for comment in data:
    # Do stuff

( len(data) returns the length of data , that is the number of items in the list.)

You are incorrectly iterating your list.

Option 1:

for index in range(0, len(data)):
    print(data[index])

Option 2:

for comment in data:
    print(comment['comment'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM