-5

I am trying to print a list of names using the following program

def search():
    with open('business_ten.json') as f:
        data=f.read()
        jsondata=json.loads(data)


    for row in jsondata['rows']:
        #print row['text']
        a=str(row['name'])

        #print a    
        return a


search()

If I put the return statement , it doesnt print , but if i put the print statement it works I want the return statement to work. I want the return statement instead of the print statement

mhawke
  • 84,695
  • 9
  • 117
  • 138
dipit
  • 105
  • 2
  • 5
  • 8

4 Answers4

0

This is due to indentation problem so that your return statement is not working. Put for loop with in search

def search():
    with open('business_ten.json') as f:
        data=f.read()
        jsondata=json.loads(data)
        for row in jsondata['rows']:
            a=str(row['name'])  
            yield a

data = search()
print list(data)

or

print list(search())
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
0

You cannot return from inside a loop, as the method will just finish after the first part of the loop. It seems like you need to print the a, append a to a list of your data, then after the loop has finished, return said list.

Also your indentation is very... interesting. I'm not sure if that's an issue with how you have copied over your code, or if that is actually what your code looks like, however I would imagine the former otherwise it would have never run. Could you possibly edit the question to correct the issue?

Benjamin James Drury
  • 2,353
  • 1
  • 14
  • 27
0

I guess this is what you want, but you could have explained it better...

def search():
    with open('business_ten.json') as f:
        data=f.read()
        jsondata=json.loads(data)
        for row in jsondata['rows']:
            a=str(row['name'])  
            yield a

print list(search())
Rusty
  • 904
  • 4
  • 10
0

Create a list of all strings you were printing earlier and return that list.

def search():
    with open('business_ten.json') as f:
        data=f.read()
        jsondata=json.loads(data)
    return_data = []
    for row in jsondata['rows']:
        #print row['text']
        a=str(row['name'])

        #print a
        return_data.append(a)

    return return_data


print(search())
Ashwani
  • 1,938
  • 11
  • 15