Search code examples
gspread

Python convert Json string to for each


I'm reading a google spreadsheet with gspread using the sheet.get_all_records(), it outputs the following:

[{"name": "test 0", "name1": "test 1", "name2": "test 2", "name3": "test 3"}, {"name": "test 0", "name1": "test 1", "name2": "test 2", "name3": "test 3"}, {"name": "test 0", "name1": "test 1", "name2": "test 2", "name3": "test 3"}, {"name": "test 0", "name1": "test 1", "name2": "test 2", "name3": "test 3"}]

I like to treat each row separatly:

list_of_hashes = sheet.get_all_records()
json_obj = json.dumps(list_of_hashes)
for line in json_obj:
   print (line['name'])
   print (line['name1'])

i get the error

TypeError: string indices must be integers

like it's not recognizing the Json

any idea how to solve this


Solution

  • How about a following modification?

    json.dumps() is used for retrieving a JSON object as a string. I think that in order to modify your script, there are following 2 patterns.

    Pattern 1:

    From :

    json_obj = json.dumps(list_of_hashes)
    

    To :

    json_obj = json.loads(json.dumps(list_of_hashes))
    

    Pattern 2:

    If sheet.get_all_records() returns a JSON object, you can directly use the returned values to for loop as follows.

    json_obj = sheet.get_all_records()
    for line in json_obj:
       print (line['name'])
       print (line['name1'])
    

    If I misunderstand your question, I'm sorry.